clear all
#delimit ;
*version 11.2;
set mem 4050m;
set matsize 3000;
set maxvar 32767;
set more off;
cap log close;


*************** Imputations *******************;
/* To make inferences from the five multiply imputed datasets one has (1) first to analyze
each of the five datasets by complete-data methods and (2) then combine the results
Look at "user guide" */;

*************************** 2002 *************************************;
**********************************************************************;
foreach x in 1 2 3 4 5{; 


cd "H:\Mi unidad\Grant_new\EFF\Imputation`x'";



use seccion6_2002_imp`x'.dta, clear;

joinby h_number using otras_secciones_2002_imp`x'.dta;

gen year=2002;

********************************************************************;
** Annual and monthly consumer price index to be used (base 2010) **;
********************************************************************;

gen acpi=78.65;
replace acpi=86.06 if year==2005;
replace acpi=94.66 if year==2008;
replace acpi=100 if year==2011;

gen mcpi=82.73 					 /* mean oct02-may03 */;
replace mcpi=91.14 if year==2005 /* mean nov05-may06 */;
replace mcpi=98.10 if year==2008 /* mean nov08-jun09 */;
replace mcpi=104.33 if year==2011 /* mean oct11-apr12 */;

********************************************************************;
*NET WEALTH AND INCOME;

*1.- FOR THE PERCENTAGE OF HOUSEHOLDS OWNING THAT ASSET;

*REAL ASSETS;

*MAIN RESIDENCE;
*To calculate the percentage of households that own their main residence we use the variable p2_1;
gen owner=0;
replace owner=1 if p2_1==2;

gen renter=0 /*renter or (only 2014) renter with purchase option*/;
replace renter=1 if p2_1==1;

gen freeuse=0;
replace freeuse=1 if p2_1==3;

*Properties RENTED;
*HOW MUCH DO YOU CURRENTLY PAY EACH MONTH IN RENT?;
rename p2_31 pay_rent;



*OTHER REAL ESTATE PROPERTIES;
*To calculate the percentage of households that own other real estate properties we use the variable np2_32;

gen np2_32=((p2_32==1 & p2_33>=1 & p2_33~=. & p2_39_1>0 & p2_39_1~=.)|
            (p2_32==1 & p2_33>=2 & p2_33~=. & p2_39_2>0 & p2_39_2~=.)|
            (p2_32==1 & p2_33>=3 & p2_33~=. & p2_39_3>0 & p2_39_3~=.)|
            (p2_32==1 & p2_33>3  & p2_33~=. & p2_39_4>0 & p2_39_4~=.));

gen othowner=.;
replace othowner=1 if np2_32==1;
replace othowner=0 if np2_32==0;

*JEWELLERY, WORKS OF ART, ANTIQUES;
*To calculate the percentage of households that own jewellery, works of art and antiques we use the variable p2_82;
gen np2_82=(p2_82==1 & p2_84>0 & p2_84~=.);

gen jewel=.;
replace jewel=0 if np2_82==0;
replace jewel=1 if np2_82==1;


*VALOR DEL NEGOCIO POR TRABAJOS POR CUENTA PROPIA;
*VALUE OF BUSINESSES RELATED TO SELF-EMPLOYMENT;
gen haveneg=(p6_1c2_1==1|p6_1c2_2==1|p6_1c2_3==1|p6_1c2_4==1|p6_1c2_5==1|p6_1c2_6==1| p6_1c2_7==1| p6_1c2_8==1| p6_1c2_9==1);


*PRIMERO;
*CALCULAR PARA CADA TRABAJO POR CTA PROPIA DE CADA MIEMBRO LOS VALORES DE 
 *(i)INMUEBLES Y EDIFICIOS,DESCONTANDO EL VALOR DE LOS ACTIVOS YA DECLARADOS COMO PROPIEDADES INMOBILIARIAS

 *(ii)NEGOCIO INCLUIDO MAQUINARIA Y VEHICULOS. (AQUI NO SE DESCUENTAN VEHICULOS YA INCLUIDOS PORQUE NO SE CONSIDERAN VEHICULOS EN RIQUEZA SINO QUE FORMAN PARTE DE NEGOCIO);

*LUEGO SE SUMAN ESTOS DOS CONCEPTOS DE VALOR NETO;
*LUEGO A ESA SUMA SE LE APLICA EL PORCENTAJE QUE PERTENECE AL MIEMBRO (PARA PROFESIONALES, PROP.UNICOS, AUTONOMOS -opcion 1 en las p6_37- SE SUPONE QUE ES 1);

*FIRST;
*DETERMINE FOR EACH SELF-EMPLOYMENT JOB OF EACH MEMBER THE VALUES OF
 *(i)REAL ESTATE PROPERTIES AND BUILDINGS, SUBSTRACTING THE VALUE OF THE ASSETS ALREADY DECLARED AS REAL ESTATE PROPERTIES
 *(ii)BUSINESS INCLUDING MACHINERY AND VEHICLES. (HERE WE DO NOT SUBSTRACT VEHICLES ALREADY INCLUDED BECAUSE VEHICLES ARE NOT CONSIDERED WEALTH IF THEY ARE NOT PART OF A BUSINESS);  
 
*THEN BOTH NET VALUES ARE ADDED;
*THEN TO THAT RESULT WE APPLY THE PERCENTAGE THAT BELONGS TO THE MEMBER (FOR INDEPENDENT PROFESSIONALS, SOLE PROPRIETORS, SELF-EMPLOYED.-option 1 in p6_37- is assumed);


forvalues m=1/6   {;

	forvalues j=1/3 {;

	display _newline(1) `m' `j';

	gen valter_`m'_`j'=0;
	gen valneg_`m'_`j'=0;
	
	gen indter_`m'_`j'=(p6_391_`m'_`j'==1);
	gen indc1_`m'_`j'=(p6_392c1_`m'_`j'==1);
	gen indc2_`m'_`j'=(p6_392c2_`m'_`j'==1);
	gen indc3_`m'_`j'=(p6_392c3_`m'_`j'==1);
	gen indc4_`m'_`j'=(p6_392c4_`m'_`j'==1);
	gen indc5_`m'_`j'=(p6_392c5_`m'_`j'==1);

	replace valter_`m'_`j'=p6_39_`m'_`j' if (p6_39_`m'_`j'>0 & p6_39_`m'_`j'~=.);
	replace valter_`m'_`j'=valter_`m'_`j'- p2_5*(indter_`m'_`j')*(indc1_`m'_`j') 
	if (p2_5>0 & p2_5~=.);

	replace valter_`m'_`j'=valter_`m'_`j'- p2_39_1*(indter_`m'_`j')*(indc2_`m'_`j') 
	if (p2_39_1>0 & p2_39_1~=.);
	replace valter_`m'_`j'=valter_`m'_`j'- p2_39_2*(indter_`m'_`j')*(indc3_`m'_`j') 
	if (p2_39_2>0 & p2_39_2~=.);
	replace valter_`m'_`j'=valter_`m'_`j'- p2_39_3*(indter_`m'_`j')*(indc4_`m'_`j') 
	if (p2_39_3>0 & p2_39_3~=.);
	replace valter_`m'_`j'=valter_`m'_`j'- p2_39_4*(indter_`m'_`j')*(indc5_`m'_`j') 
	if (p2_39_4>0 & p2_39_4~=.);

	display _newline(1);

	replace valter_`m'_`j'=0 if valter_`m'_`j'<0;


	display _newline(1);
	
	replace valneg_`m'_`j'=p6_40_`m'_`j' if (p6_40_`m'_`j'>0 & p6_40_`m'_`j'~=.);
      
	display _newline(1);
	gen coef_`m'_`j'=1;
	replace coef_`m'_`j'=(p6_3824_`m'_`j')/100 
	if (p6_3824_`m'_`j'>0 & p6_3824_`m'_`j'~=. & p6_37_`m'_`j'==2);

	replace coef_`m'_`j'=(p6_3832_`m'_`j')/100 
	if (p6_3832_`m'_`j'>0 & p6_3832_`m'_`j'~=. & p6_37_`m'_`j'==3);
	gen valind_`m'_`j'=(valter_`m'_`j'+valneg_`m'_`j')*coef_`m'_`j';
	
	};

};


*SEGUNDO;
*PARA NO REPETIR VALORES DE UN MISMO NEGOCIO EN QUE TRABAJAN VARIOS MIEMBROS DEL HOGAR:
 *(i) PARA MIEMBROS EMPRESA FAMILIAR O NO FAMILIAR.
     (-opciones 2 o 3 en la p6_37)  COMO SE LES APLICA EL COEFICIENTE INDIVIDUAL,  SE SUMA Y NO SE DUPLICA 
* (ii)PARA PROFESIONALES, AUTONOMOS (opcion 1 en p6_37) SE HACE LO SIGUIENTE
	*(a) SE SUMA SIEMPRE QUE DIGA QUE SOLO EL TRABAJA EN ESE NEGOCIO (P6_35==1)
	*(b) PARA P6_35>1
		*SE SUMA SIEMPRE SI ES LA PERSONA DE REFERENCIA;
		*SI ES 2º MIEMBRO SOLO SE SUMA 
        *    SI NO HAY NINGUN TRABAJO COMO CTA PROPIA
		* DE LA PERSONA DE REFERENCIA EN QUE P6_35>1;
		*SI ES 3er MIEMBRO SOLO SE SUMA 
            * SI NO HAY NINGUN TRABAJO COMO CTA PROPIA
		* DE LA PERSONA DE REFERENCIA EN QUE P6_35>1 
           *  NI NINGUN TRABAJO COMO CTA PROPIA
		* DEL 2º MIEMBRO EN QUE P6_35>1;
		*Y ASI SUCESIVAMENTE PARA EL RESTO DE MIEMBROS;

*SECOND;
*TO AVOID DOUBLE COUNTING OF THE SAME BUSINESS IN WHICH SEVERAL HOUSEHOLD MEMBERS ARE WORKING:
 *(i) FOR MEMBERS OR PARTNERS OF A FAMILY OR NON-FAMILY FIRM.
 *    (-options 2 or 3 in p6_37)  SINCE INDIVIDUAL COEFFICIENTS ARE APPLIED, NO DOUBLE COUNTING
 *(ii)FOR PROFESSIONALS, SELF-EMPLOYED (OPTION 1 IN P6_37):
(a)	ADDED WHENEVER THE HOUSEHOLD MEMBER IS THE ONLY ONE WORKING IN THAT BUSINESS (P6_35==1)
(b)	FOR P6_35>1
*IT IS ALWAYS ADDED IF THE HOUSEHOLD MEMBER IS THE REFERENCE PERSON;
*IF THE HOUSEHOLD MEMBER IS THE SECOND MEMBER IT IS ONLY ADDED IF THERE IS NO SELF-EMPLOYMENT JOB OF THE REFERENCE PERSON IN WHICH P6_35>1;
*IF THE HOUSEHOLD MEMBER IS THE THIRD MEMBER IT IS ONLY ADDED IF THERE IS NO SELF-EMPLOYMENT JOB OF THE REFERENCE PERSON IN WHICH P6_35>1 NOR ANY SELF-EMPLOYMENT JOB OF THE SECOND MEMBER IN WHICH P6_35>1;
*THE SAME PROCEDURE APPLIES FOR THE REST OF THE HOUSEHOLD MEMBERS; 


gen valhog=0;

gen noinsum2=(p6_35_1_1>1 & p6_35_1_1~=. & p6_37_1_1==1|
		  p6_35_1_2>1 & p6_35_1_2~=. & p6_37_1_2==1|
		  p6_35_1_3>1 & p6_35_1_3~=. & p6_37_1_3==1);
gen noinsum3=(noinsum2==1|
		  p6_35_2_1>1 & p6_35_2_1~=. & p6_37_2_1==1|
		  p6_35_2_2>1 & p6_35_2_2~=. & p6_37_2_2==1|
		  p6_35_2_3>1 & p6_35_2_3~=. & p6_37_2_3==1);
gen noinsum4=(noinsum3==1|
		  p6_35_3_1>1 & p6_35_3_1~=. & p6_37_3_1==1|
		  p6_35_3_2>1 & p6_35_3_2~=. & p6_37_3_2==1|
		  p6_35_3_3>1 & p6_35_3_3~=. & p6_37_3_3==1);
gen noinsum5=(noinsum4==1|
		  p6_35_4_1>1 & p6_35_4_1~=. & p6_37_4_1==1|
		  p6_35_4_2>1 & p6_35_4_2~=. & p6_37_4_2==1|
		  p6_35_4_3>1 & p6_35_4_3~=. & p6_37_4_3==1);
gen noinsum6=(noinsum5==1|
		  p6_35_5_1>1 & p6_35_5_1~=. & p6_37_5_1==1|
		  p6_35_5_2>1 & p6_35_5_2~=. & p6_37_5_2==1|
		  p6_35_5_3>1 & p6_35_5_3~=. & p6_37_5_3==1);
	

forvalues m=1/6   {;
	forvalues j=1/3 {;

	replace valhog=valhog+valind_`m'_`j' if ((valind_`m'_`j'>0 & valind_`m'_`j'~=.) & (
		p6_37_`m'_`j'==2|p6_37_`m'_`j'==3|
		p6_37_`m'_`j'==1 & p6_35_`m'_`j'==1|

		p6_37_`m'_`j'==1 & p6_35_`m'_`j'>1 & p6_35_`m'_`j'~=. & `m'==1|
            p6_37_`m'_`j'==1 & p6_35_`m'_`j'>1 & p6_35_`m'_`j'~=. & `m'==2 & noinsum2==0|
            p6_37_`m'_`j'==1 & p6_35_`m'_`j'>1 & p6_35_`m'_`j'~=. & `m'==3 & noinsum3==0|
            p6_37_`m'_`j'==1 & p6_35_`m'_`j'>1 & p6_35_`m'_`j'~=. & `m'==4 & noinsum4==0|

            p6_37_`m'_`j'==1 & p6_35_`m'_`j'>1 & p6_35_`m'_`j'~=. & `m'==5 & noinsum5==0|
            p6_37_`m'_`j'==1 & p6_35_`m'_`j'>1 & p6_35_`m'_`j'~=. & `m'==6 & noinsum6==0 ));

	};
};

*Para calcular las proporciones de hogares con algo de cuenta propia generamos una nueva variable que tiene en cuenta que se declare un valor positivo para el negocio;
*To calculate the percentages of households with some business we generate a new variable that takes into account that a positive value is held for the business; 

gen havenegval =(haveneg==1 & valhog>0);

 

*ALGUN TIPO DE ACTIVO REAL;
*SOME KIND OF REAL ASSET;

gen  tienereal=(p2_1==2|p2_32==1|p2_82==1| havenegval==1);


*ACTIVOS FINANCIEROS;
*FINANCIAL ASSETS;


*ACCOUNTS AND DEPOSITS USABLE FOR PAYMENTS;
*To calculate the percentage of households that own accounts and deposits usable for payments and that declare a strictly positive value 
*for the balance of those accounts we generate a new variable;

gen np4_5=(p4_5==1 & p4_7_3>0 & p4_7_3~=.);
rename np4_5 account_pay;
label var account_pay "households that own accounts and deposits usable for payments and that declare a strictly positive value";

*LISTED SHARES;
*To calculate the percentage of households that own listed shares we use the variable p4_10;
rename p4_10 listshare;
label var listshare "household that own listed shares";


*UNLISTED SHARES AND OTHER EQUITY;
*To calculate the percentage of households that own unlisted shares and other equity and that declare a strictly positive
* value for that portfolio we generate a new variable;

gen np4_18=(p4_18==1 & p4_24>0 & p4_24~=.);
rename np4_18 unlistshare;
label var unlistshare "household that own unlisted shares and other equity";


*FIXED-INCOME SECURITIES;
*To calculate the percentage of households that own fixed-income securities we use the variable p4_33;
rename p4_33 fixsec;
label var fixsec "household that own fixed-income securities ";

*MUTUAL FUNDS (FFII);
*To calculate the percentage of households that own mutual funds we use the variable p4_27;
rename p4_27 mutfunds;
label var mutfunds "household that own mutual funds";

*CUENTAS VIVIENDA Y CUENTAS NO UTILIZABLES PARA REALIZAR PAGOS;
*Para calcular la proporción de hogares que poseen cuentas y depósitos no utilizables para realizar pagos generamos una nueva variable cuentas;

*HOUSE-PURCHASE SAVINGS ACCOUNTS AND ACCOUNTS NOT USABLE FOR PAYMENTS;
*To calculate the percentage of households that own accounts and deposits not usable for payments we generate a new variable cuentas;

gen cuentas=(p4_3==1|p4_4==1);
rename cuentas account_nopay;
label var account_nopay "household that own accounts and deposits not usable for payments";


*PENSION SCHEMES (plan pensiones);
*To calculate the percentage of households that own pension schemes we use the variable p5_1;
rename p5_1 penplan;
label var penplan "household that own pension schemes";

*SEGUROS DE VIDA;
*Para calcular la proporción de hogares que tienen seguros tipo unit linked o mixto generamos una nueva variable;

*To calculate the percentage of households that own unit-linked or mixed life insurance we generate a new variable;

gen seguro=(p5_13_1==2| p5_13_2==2| p5_13_3==2| p5_13_4==2| p5_13_5==2| p5_13_6==2| p5_13_1==3| p5_13_2==3| p5_13_3==3| p5_13_4==3| p5_13_5==3| p5_13_6==3);
rename seguro lifeinsur;
label var lifeinsur "household that own unit-linked or mixed life insurance";

*PLANES DE PENSIONES INCLUYENDO SEGUROS DE VIDA DE INVERSION O MIXTOS;
*PENSION SCHEMES INCLUDING UNIT-LINKED OR MIXED LIFE INSURANCE;

gen penseg=(penplan==1|lifeinsur==1);

*OTHER FINANCIAL ASSETS; 

*To calculate the percentage of households to whom the business or other people owe money we generate the variable sideuda; 


*PROGRAMA PARA CALCULAR LO QUE LES DEBEN LOS NEGOCIOS A LOS DISTINTOS MIEMBROS DEL HOGAR (P6_44);
*PROGRAM TO OBTAIN WHAT THE BUSINESSES OWE TO THE DIFFERENT HOUSEHOLD MEMBERS (P6_44);

gen valdeuhog=0;
gen havedeuhog=0;

forvalues m=1/6   {;

	forvalues j=1/3 {;

	display _newline(1) `m' `j';
	

	replace valdeuhog=valdeuhog+p6_44_`m'_`j' 
	if (p6_44_`m'_`j'>0 & p6_44_`m'_`j'~=.);

	replace havedeuhog=1 if (p6_43_`m'_`j'==1);


	};

};
	
gen sideuda=((havedeuhog ==1 & valdeuhog>0)|(p4_37==1 & p4_38>0 & p4_38~=.));
rename sideuda creditor;
label var creditor "household to whom the business or other people owe money";

*ALGUN TIPO DE ACTIVO FINANCIERO;
*SOME TYPE OF FINANCIAL ASSET;

gen tienefin=(account_pay==1|listshare==1|unlistshare==1|fixsec==1|mutfunds==1|account_nopay==1|penplan==1|lifeinsur==1|creditor==1);

*ALGUN TIPO DE ACTIVO;
*SOME TYPE OF ASSET;

gen tiene=(tienereal==1|tienefin==1);
rename tiene anyasset;




*2.- PARA EL VALOR DE DICHOS ACTIVOS;
*2.- FOR THE VALUE OF THOSE ASSETS;

*ACTIVOS REALES;
*REAL ASSETS;

*MAIN RESIDENCE;
*To obtain the value of the main residence we use the variable p2_5;
rename p2_5 vmresid;
label var vmresid "value of the main residence";

*OTHER REAL ESTATE PROPERTIES;
*To obtain the value of the other real estate properties we generate a new variable;

gen otraspr=0;
replace otraspr=otraspr+p2_39_1*(p2_37_1/100) if (p2_33>=1 & p2_33~=. & p2_39_1>=0 & p2_39_1~=. & p2_37_1>0 & p2_37_1~=.);
replace otraspr=otraspr+p2_39_2 *(p2_37_2/100) if (p2_33>=2 & p2_33~=. & p2_39_2>=0 & p2_39_2~=. & p2_37_2>0 & p2_37_2~=.);
replace otraspr=otraspr+p2_39_3* (p2_37_3/100) if (p2_33>=3 & p2_33~=. & p2_39_3>=0 & p2_39_3~=. & p2_37_3>0 & p2_37_3~=.);
replace otraspr=otraspr+p2_39_4 if (p2_33>3 & p2_33~=. & p2_39_4>=0 & p2_39_4~=.);

rename otraspr vothprop;
label var vothprop "value of the other real estate properties";


*JEWELLERY, WORKS OF ART, ANTIQUES;
*To obtain the value of the jewellery, works of art and antiques we use the variable p2_84;
rename p2_84 vjewel;
label var vjewel "value of the jewellery, works of art and antiques";

*VALOR DEL NEGOCIO POR TRABAJOS POR CUENTA PROPIA;
*la mediana del valor del negocio será la mediana de valhog if havenegval==1; 

*TBD;

*VALUE OF THE BUSINESS RELATED TO SELF-EMPLOYMENT;
*The median of the business value is equal to the median of valhog if havenegval==1;


*ACTIVOS FINANCIEROS;
*FINANCIAL ASSETS;

*CUENTAS Y DEPOSITOS UTILIZABLES PARA REALIZAR PAGOS;
*Para calcular el saldo de las cuentas y depósitos para realizar pagos utilizamos la variable p4_7_3;


*ACCOUNTS AND DEPOSITS USABLE FOR PAYMENTS;
*To obtain the balance of the accounts and deposits usable for payments we use the variable p4_7_3;
rename p4_7_3 vaccount_pay;



*ACCIONES COTIZADAS EN BOLSA;
*Para calcular el valor de las acciones cotizadas utilizamos la variable p4_15;


*LISTED SHARES;
*To obtain the value of the listed shares we use the variable p4_15;
rename p4_15 vlistshare;

*ACCIONES NO COTIZADAS EN BOLSA Y PARTICIPACIONES;
*Para calcular el valor de las acciones no cotizadas y participaciones utilizamos la variable p4_24;

*UNLISTED SHARES ANDOTHER EQUITY;
*To obtain the value of the unlisted shares and other equity we use the variable p4_24;
rename p4_24 vunlist;

*VALORES DE RENTA FIJA;
*Para calcular el valor de los valores de renta fija utilizamos la variable p4_35;

*FIXED-INCOME SECURITIES;
*To obtain the value of the fixed-income securities we use the variable p4_35;

rename p4_35 vfixsec;

*FONDOS DE INVERSION;
*Para calcular el valor total de los fondos de inversión utilizamos la variable allf calculada como (i) la suma de los valores de cada uno de los fondos 
*de inversión que posee el hogar (p4_31_i, i=1,…,10) si el número de estos fondos es menor o igual a 10, y (ii) el valor total de los fondos de inversión 
*del hogar si posee más de 10 fondos (p4_28a);

*MUTUAL FUNDS;
*To obtain the total value of mutual funds we use the variable allf calculated as (i) the addition of the values of each mutual fund that the household
* owns (p4_31_i, i=1,…,10) if the number of these funds is 10 or less, and (ii) the household mutual funds’ total value if this one owns more than 10 (p4_28a);

egen allf=rowtotal(p4_31*);
replace allf=p4_28a if p4_28>10;
label var allf "Total value of mutual funds";


*CUENTAS VIVIENDA Y CUENTAS NO UTILIZABLES PARA REALIZAR PAGOS;
*Para calcular el saldo de las cuentas y depósitos no utilizables para realizar pagos generamos una nueva variable;

*HOME-PURCHASE SAVINGS ACCOUNTS AND ACCOUNTS NOT USABLE FOR PAYMENTS;
*To obtain the balance of the accounts and deposits not usable for payments we generate a new variable;  

gen salcuentas=0;
replace salcuentas = salcuentas +p4_7_1 if (p4_3==1 & p4_7_1>=0 & p4_7_1~=. );
replace salcuentas = salcuentas + p4_7_2 if (p4_4==1 & p4_7_2>=0 & p4_7_2~=.);
rename salcuentas vaccount_nopay;
label var vaccount_nopay "balance of the accounts and deposits not usable for payments";

*PLANES DE PENSIONES;
*Para calcular valor actualizado de los planes de pensiones generamos una nueva variable;

*PENSION SCHEMES;
*To obtain the current value of the pension schemes we generate a new variable;

gen valor=0; 

replace valor = valor +p5_7_1 if (penplan==1 & p5_7_1>=0 & p5_7_1~=. ); 
replace valor = valor + p5_7_2 if (penplan==1 & p5_7_2>=0 & p5_7_2~=.);
replace valor = valor + p5_7_3 if (penplan==1 & p5_7_3>=0 & p5_7_3~=.);
replace valor = valor + p5_7_4 if (penplan==1 & p5_7_4>=0 & p5_7_4~=.);
replace valor = valor + p5_7_5 if (penplan==1 & p5_7_5>=0 & p5_7_5~=.);
replace valor = valor + p5_7_6 if (penplan==1 & p5_7_6>=0 & p5_7_6~=.);
replace valor = valor + p5_7_7 if (penplan==1 & p5_7_7>=0 & p5_7_7~=.);
replace valor = valor + p5_7_8 if (penplan==1 & p5_7_8>=0 & p5_7_8~=.);

rename valor vpenplan;
label var vpenplan "current value of the pension schemes";

*No consideramos las mutualidades;
*We do not consider mutual insurance;

*SEGUROS DE VIDA;
*Para calcular el valor de estos seguros tipo unit linked o mixto generamos una nueva variable;

*LIFE INSURANCE;
*To obtain the value of the unit-linked or mixed life insurance we generate a new variable;


gen valseg=0;

replace valseg = valseg +p5_14_1 if ((p5_13_1==2| p5_13_1==3) & p5_14_1>0 & p5_14_1~=.);
replace valseg = valseg +p5_14_2 if ((p5_13_2==2| p5_13_2==3) & p5_14_2>0 & p5_14_2~=.);
replace valseg = valseg +p5_14_3 if ((p5_13_3==2| p5_13_3==3) & p5_14_3>0 & p5_14_3~=.);
replace valseg = valseg +p5_14_4 if ((p5_13_4==2| p5_13_4==3) & p5_14_4>0 & p5_14_4~=.);
replace valseg = valseg +p5_14_5 if ((p5_13_5==2| p5_13_5==3) & p5_14_5>0 & p5_14_5~=.);
replace valseg = valseg +p5_14_6 if ((p5_13_6==2| p5_13_6==3) & p5_14_6>0 & p5_14_6~=.);

rename valseg vlifeinsur;
label var vlifeinsur "value of the unit-linked or mixed life insurance";

*PLANES DE PENSIONES INCLUYENDO SEGUROS DE VIDA DE INVERSION O MIXTOS;
*PENSION SCHEMES INCLUDING UNIT-LINKED OR MIXED LIFE INSURANCE;

gen valpenseg=vpenplan+vlifeinsur;
rename valpenseg vpeninsur;
label var vpeninsur "value of pension schemes plus unit-linked or mixed life insurance";

*OTROS ACTIVOS FINANCIEROS;
*Para calcular el valor de la mediana de lo que se debe al hogar, utilizamos las variables valdeuhog y p4_38 y generamos una nueva variable;

*OTHER FINANCIAL ASSETS;
*To obtain the median of how much is owed to the household, we use the variables valdeuhog and p4_38 and generate a new variable; 

gen odeuhog=0;

replace odeuhog = odeuhog +valdeuhog if (valdeuhog>0);
replace odeuhog = odeuhog +p4_38 if (p4_38>0 & p4_38~=.);

rename odeuhog vcreditor;
label var vcreditor "how much is owed to the household";

*CUADRO 7: PROPORCION DE HOGARES Y MEDIANA DEL VALOR DE LOS DISTINTOS TIPOS DE DEUDA PENDIENTES;
*TABLE 7: PERCENTAGE OF HOUSEHOLDS AND VALUE’S MEDIAN OF THE DIFFERENT TYPES OF OUTSTANDING DEBT;

*DEUDAS  CLASIFICADAS POR TIPO DE ACTIVO INMOBILIARIO (TODO TIPO DE PRESTAMOS);
*DEBT CLASSIFIED BY TYPE OF REAL ESTATE ASSET (ALL KIND OF LOANS);

*VIVIENDA PRINCIPAL;
*MAIN RESIDENCE;

*Para calcular la proporción de hogares que tienen deudas pendientes de préstamos solicitados para la adquisición de la vivienda principal, utilizamos p2_8;
*To obtain the percentage of households that have outstanding debt from loans used to purchase their main residence, we use p2_8;
rename p2_8 debtmresid;
label var debtmresid "have outstanding debt from loans used to purchase main residence";

*Para calcular el valor de las deudas pendientes de préstamos solicitados para la adquisición de la vivienda principal, generamos una nueva variable;
*To obtain the value of the outstanding debts from loans used to purchase their main residence, we generate a new variable;

gen dvivpral=0;

replace dvivpral= dvivpral +p2_12_1 if  (p2_8a>=1 & p2_8a~=. & p2_12_1>0 & p2_12_1~=.);

replace dvivpral= dvivpral + p2_12_2 if (p2_8a>=2 & p2_8a~=. &  p2_12_2>0 & p2_12_2~=.);

replace dvivpral= dvivpral +p2_12_3  if (p2_8a>=3 & p2_8a~=. & p2_12_3>0 & p2_12_3~=.);

replace dvivpral= dvivpral +p2_12_4  if (p2_8a>3 & p2_8a~=. & p2_12_4>0 & p2_12_4~=.);

rename dvivpral vdebtmresid;
label var vdebtmresid "value of outstanding debts from loans used to purchase main residence";

*OTRAS PROPIEDADES INMOBILIARIAS DIFERENTES DE LA VIVIENDA PRINCIPAL;
*OTHER REAL ESTATE PROPERTIES DIFFERENT FROM THE MAIN RESIDENCE;

*Para calcular la proporción de hogares que tienen deudas pendientes de préstamos solicitados para la adquisición de otras propiedades inmobiliarias diferentes de la vivienda principal, generamos una nueva variable;

*To obtain the percentage of households that have outstanding debts from loans used to purchase other real estate properties different from the main 
*residence, we generate a new variable;

gen dpdte=(p2_50_1==1|p2_50_2==1|p2_50_3==1|p2_50_4==1);
rename dpdte debtothprop;
label var debtothprop "have outstanding debts from loans used to purchase other real estate properties";

*Para calcular el valor de las deudas pendientes de préstamos solicitados para la adquisición de otras propiedades inmobiliarias diferentes de la vivienda principal, generamos cuatro nuevas variables;

*To obtain the value of the outstanding debts from loans used to purchase other real estate properties different from the main residence, we generate
* four new variables;

*PARA LA PRIMERA PROPIEDAD INMOBILIARIA;
*FOR THE FIRST REAL ESTATE PROPERTY;

gen dprop1=0;

replace dprop1= dprop1+p2_55_1_1 if (p2_51_1>=1 & p2_51_1~=.  &  p2_55_1_1>0 & p2_55_1_1~=.);

replace dprop1= dprop1+ p2_55_1_2 if (p2_51_1>=2 & p2_51_1~=.  & p2_55_1_2>0 & p2_55_1_2~=.);

replace dprop1= dprop1+p2_55_1_3  if (p2_51_1>=3 & p2_51_1~=.  & p2_55_1_3>0 & p2_55_1_3~=.);


*PARA LA SEGUNDA PROPIEDAD INMOBILIARIA;
*FOR THE SECOND REAL ESTATE PROPERTY;

gen dprop2=0;

replace dprop2= dprop2+p2_55_2_1 if (p2_51_2>=1 & p2_51_2~=. & p2_55_2_1>0 & p2_55_2_1~=.);

replace dprop2= dprop2+ p2_55_2_2 if (p2_51_2>=2 & p2_51_2~=. & p2_55_2_2>0 & p2_55_2_2~=.);

replace dprop2= dprop2+ p2_55_2_3  if (p2_51_2>=3 & p2_51_2~=. & p2_55_2_3>0 & p2_55_2_3~=.);


*PARA LA TERCERA PROPIEDAD INMOBILIARIA;
*FOR THE THIRD REAL ESTATE PROPERTY;

gen dprop3=0;

replace dprop3= dprop3+p2_55_3_1 if (p2_51_3>=1 & p2_51_3~=. & p2_55_3_1>0 & p2_55_3_1~=.);

replace dprop3= dprop3+ p2_55_3_2 if (p2_51_3>=2 & p2_51_3~=. & p2_55_3_2>0 & p2_55_3_2~=.);

replace dprop3= dprop3+ p2_55_3_3  if (p2_51_3>=3 & p2_51_3~=. & p2_55_3_3>0 & p2_55_3_3~=.);


*PARA EL RESTO DE PROPIEDADES INMOBILIARIAS CUANDO HAY MAS DE TRES;
*FOR THE REST OF REAL ESTATE PROPERTIES WHEN THESE ARE MORE THAN THREE;

gen dprop4=0;

replace dprop4= dprop4+p2_55_4 if (p2_55_4>0 & p2_55_4~=.);

forvalues i=1(1)4{;
rename dprop`i' vdebtprop`i';
};

label var vdebtprop1 "value of the outstanding debts from loans used to purchase other real estate property #1";
label var vdebtprop2 "value of the outstanding debts from loans used to purchase other real estate property #2";
label var vdebtprop3 "value of the outstanding debts from loans used to purchase other real estate property #3";
label var vdebtprop4 "value of the outstanding debts from loans used to purchase other real estate properties #4";


*CONSIDERANDO CONJUNTAMENTE TODAS LAS PROPIEDADES INMOBILIARIAS DIFERENTES DE LA VIVIENDA PRINCIPAL;
*CONSIDERING ALL REAL ESTATE PROPERTIES DIFFERENT FROM THE MAIN RESIDENCE;

gen deuoprop= vdebtprop1+ vdebtprop2+ vdebtprop3+ vdebtprop4 ; 
rename deuoprop vdebtothprop;
label var vdebtothprop "value of the outstanding debts from loans used to purchase other real estate properties";

*DEUDAS PENDIENTES DE PRESTAMOS SOLICITADOS PARA LA ADQUISICION DE LA VIVIENDA PRINCIPAL CON GARANTIA HIPOTECARIA;
*OUTSTANDING DEBTS FROM LOANS WITH MORTGAGE GUARANTEE USED FOR THE PURCHASE OF THE MAIN RESIDENCE;

*Para calcular la proporción de hogares que tienen deudas pendientes de préstamos CON garantía hipotecaria solicitados para la adquisición de la vivienda principal, generamos una nueva variable;
*To obtain the percentage of households that have outstanding debts from loans with mortgage guarantee used for the purchase of the main residence, 
* we generate a new variable;

gen dpdtehipo = (p2_9_1==1|p2_9_2==1|p2_9_3==1|p2_9_4==1);
rename dpdtehipo mortgmresid;
label var mortgmresid " have mortgage for the purchase of the main residence";

*Para calcular el valor de las deudas pendientes de préstamos CON garantía hipotecaria solicitados para la adquisición de la vivienda principal, generamos una nueva variable;
*To obtain the value of the outstanding debts from loans with mortgage guarantee used for the purchase of the main residence, we generate a new variable;

gen deuhipv =0;

replace deuhipv= deuhipv + p2_12_1 if (p2_8a>=1 & p2_8a~=. & p2_9_1==1 & p2_12_1>0 & p2_12_1~=.);

replace deuhipv = deuhipv + p2_12_2 if (p2_8a>=2 & p2_8a~=. & p2_9_2==1 &  p2_12_2>0 & p2_12_2~=.);

replace deuhipv= deuhipv +p2_12_3  if (p2_8a>=3 & p2_8a~=. & p2_9_3==1 &  p2_12_3>0 & p2_12_3~=.);

replace deuhipv= deuhipv +p2_12_4  if (p2_8a>3 & p2_8a~=. & p2_8a~=. & p2_9_4==1 &  p2_12_4>0 & p2_12_4~=.);

rename deuhipv vmortgmresid;
label var vmortgmresid "value of outstanding mortgages for the purchase of the main residence";


*OTRAS DEUDAS PENDIENTES NO ASOCIADAS A LA ADQUISICION DE ACTIVOS INMOBILIARIOS;
*OTHER OUTSTANDING DEBT NOT RELATED TO THE PURCHASE OF REAL ESTATE ASSETS;

*DEUDAS PENDIENTES DE PRESTAMOS HIPOTECARIOS Y OTROS PRESTAMOS CON GARANTIA REAL;
*OUTSTANDING DEBTS FROM MORTGAGES AND OTHER SECURED LOANS);

*Para calcular la proporción de hogares que tienen deudas pendientes por prestamos hipotecarios y otros préstamos con garantía real generamos una nueva variable;
*To obtain the percentage of households that have outstanding debts from mortgages and other secured loans we generate a new variable;

gen hipo=(p3_2_1==1| p3_2_2==1| p3_2_3==1| p3_2_4==1|
p3_2_1==2| p3_2_2==2| p3_2_3==2| p3_2_4==2);

rename hipo mortgoth;
label var mortgoth "have mortgage for other porpuses";

*Para calcular el valor de las deudas pendientes por prestamos hipotecarios y otros préstamos con garantía real generamos una nueva variable;
*To obtain the value of the outstanding debts from mortgages and other loans with real guarantee we generate a new variable;

gen phipo=0;

replace phipo = phipo +p3_6_1 if ((p3_2_1==1|p3_2_1==2) & p3_6_1>0 & p3_6_1~=.);

replace phipo = phipo +p3_6_2 if ((p3_2_2==1| p3_2_2==2) & p3_6_2>0 & p3_6_2~=.);

replace phipo = phipo +p3_6_3 if ((p3_2_3==1| p3_2_3==2)  & p3_6_3>0 & p3_6_3~=.);

replace phipo = phipo +p3_6_4 if ((p3_2_4==1| p3_2_4==2) & p3_6_4>0 & p3_6_4~=.);



rename phipo vmortgoth;
label var vmortgoth "value of outstanding mortgages for other purposes";

*Variable capturing any kind of mortgage or secure debt ;
gen mortgage =0;
replace mortgage=1 if mortgoth==1 | mortgmresid==1;

*DEUDAS PENDIENTES DE PRESTAMOS PERSONALES;
*OUTSTANDING DEBTS FROM PERSONAL LOANS;

*Para calcular la proporción de hogares que tienen deudas pendientes por prestamos personales generamos una nueva variable;
*To obtain the percentage of households that have outstanding debts from personal loans we generate a new variable;

gen perso=(p3_2_1==3| p3_2_2==3| p3_2_3==3| p3_2_4==3);
rename perso personal;
label var personal "have outstanding debts from personal loans";

*Para calcular el valor de las deudas pendientes por prestamos personales generamos una nueva variable;
*To obtain the value of the outstanding debts from personal loans we generate a new variable;

gen pperso=0;

replace pperso = pperso +p3_6_1 if (p3_2_1==3 & p3_6_1>0 & p3_6_1~=.);

replace pperso = pperso +p3_6_2 if (p3_2_2==3 & p3_6_2>0 & p3_6_2~=.);

replace pperso = pperso +p3_6_3 if (p3_2_3==3 & p3_6_3>0 & p3_6_3~=.);

replace pperso = pperso +p3_6_4 if (p3_2_4==3 & p3_6_4>0 & p3_6_4~=.);


rename pperso vpersonal;
label var vpersonal "value of personal loans";






*OTRAS DEUDAS;
*OTHER DEBTS;

*Para calcular la proporción de hogares que tienen otras deudas pendientes generamos una nueva variable;
*To obtain the percentage of households that have other outstanding debts we generate a new variable;

gen otrasd=(p3_2_1==4| p3_2_2==4| p3_2_3==4| p3_2_4==4| p3_2_1==5| p3_2_2==5| p3_2_3==5| p3_2_4==5|  p3_2_1==6| p3_2_2==6| p3_2_3==6| p3_2_4==6|  p3_2_1==7| p3_2_2==7| p3_2_3==7|
 p3_2_4==7 | p3_2_1==8| p3_2_2==8| p3_2_3==8| p3_2_4==8 | p3_2_1==9|
 p3_2_2==9| p3_2_3==9| p3_2_4==9|  p3_2_1==97| p3_2_2==97| p3_2_3==97| p3_2_4==97 );
rename otrasd othdebt;
label var othdebt "households that have other outstanding debt";


*Para calcular el valor de las otras deudas pendientes generamos una nueva variable;
*To obtain the value of the other outstanding debts we generate a new variable;

gen potrasd =0;

replace potrasd = potrasd +p3_6_1 if ((p3_2_1==4| p3_2_1==5| p3_2_1==6| p3_2_1==7| p3_2_1==8|p3_2_1==9|
p3_2_1==97) & p3_6_1>0 & p3_6_1~=.);

replace potrasd = potrasd +p3_6_2 if ((p3_2_2==4| p3_2_2==5|  p3_2_2==6| p3_2_2==7| p3_2_2==8|p3_2_2==9|
p3_2_2==97) & p3_6_2>0 & p3_6_2~=.);

replace potrasd = potrasd +p3_6_3 if ((p3_2_3==4| p3_2_3==5| p3_2_3==6| p3_2_3==7| p3_2_3==8|p3_2_3==9|
p3_2_3==97) & p3_6_3>0 & p3_6_3~=.);

replace potrasd = potrasd +p3_6_4 if ((p3_2_4==4| p3_2_4==5| p3_2_4==6| p3_2_4==7| p3_2_4==8|p3_2_4==9|
p3_2_4==97) & p3_6_4>0 & p3_6_4~=.);


rename potrasd vothdebt;
label var vothdebt "value of the other outstanding debts";


******************************************************************************************************;
******************************************************************************************************;

*                          R A N K I N G     A: NATURE OF THE DEBT									 *;

******************************************************************************************************;
******************************************************************************************************;
gen housesec=0;
gen houseunsec=0;
gen othsecured=0;
gen consumer=0;
gen rest=0;

gen vhousesec=0;
gen vhouseunsec=0;
gen vothsecured=0;
gen vconsumer=0;
gen vrest=0;

replace vhousesec=vhousesec+p2_55_4 if p2_55_4!=. /*Consider as secured, all debts attached to fourth real state properties in advanced */;

forvalues i=1(1)4 {;
replace housesec=1 if p2_9_`i'<=2;
replace vhousesec=vhousesec+p2_12_`i' if p2_9_`i'<=2; 
replace houseunsec=1 if p2_9_`i'>2 & p2_9_`i'<=97;
replace vhouseunsec=vhouseunsec+p2_12_`i' if p2_9_`i'>2 & p2_9_`i'<=97;
};

forvalues i=1(1)3 {;
		forvalues s=1(1)3 {; 
		replace housesec=1 if p2_52_`i'_`s'<=2;
		replace vhousesec=vhousesec+p2_55_`i'_`s' if  p2_52_`i'_`s'<=2;
		replace houseunsec=1 if p2_52_`i'_`s'>2 & p2_52_`i'_`s'<=97;
		replace vhouseunsec=vhousesec+p2_55_`i'_`s' if  p2_52_`i'_`s'>2 & p2_52_`i'_`s'<=97;
};
};

forvalues i=1(1)4 {;
replace othsecured=1 if p3_2_`i'<=2;
replace vothsecured=vothsecured+p3_6_`i' if p3_2_`i'<=2;
replace consumer=1 if p3_2_`i'==3;
replace vconsumer=vconsumer+p3_6_`i' if p3_2_`i'==3;
replace rest=1 if p3_2_`i'>3 & p3_2_`i'<=97;
replace vrest=vrest+p3_6_`i' if p3_2_`i'>3 & p3_2_`i'<=97;

};

******************************************************************************************************;
******************************************************************************************************;

*                          R A N K I N G     B: OBJECTIVE OF THE DEBT (housing comprises just secured loans. 'Rest' comprises housing unsecured;							 *;

******************************************************************************************************;
******************************************************************************************************;

gen housing=0;
*gen carloan=0;
gen busloan=0;
gen restbis=0;

replace housing=1 if housesec==1;
replace restbis=1 if houseunsec==1;
forvalues i=1(1)4 {;
*replace carloan=1 if p3_3_`i'==2;
replace busloan=1 if p3_3_`i'==12;
replace housing=1 if p3_3_`i'==14 & p3_2_`i'<=2;
replace restbis=1 if p3_3_`i'==1 | p3_3_`i'==2 | p3_3_`i'==3 | p3_3_`i'==4 | p3_3_`i'==34 | p3_3_`i'==5 | p3_3_`i'==6 | p3_3_`i'==7 | p3_3_`i'==8 | p3_3_`i'==9 |
						p3_3_`i'==10 | p3_3_`i'==11 | p3_3_`i'==13 | (p3_3_`i'==14 & p3_2_`i'>2) | p3_3_`i'==15 | p3_3_`i'==97;
						

};

gen vhousing=0;
*gen vcarloan=0;
gen vbusloan=0;
gen vrestbis=0;

replace vhousing=vhousesec;
replace vrestbis=vhouseunsec;
forvalues i=1(1)4 {;
*replace vcarloan=vcarloan + p3_6_`i' if p3_3_`i'==2;
replace vbusloan=vbusloan + p3_6_`i'  if p3_3_`i'==12;
replace vhousing=vhousing + p3_6_`i' if p3_3_`i'==14 & p3_2_`i'<=2;
replace vrestbis=vrestbis + p3_6_`i' if p3_3_`i'==1 | p3_3_`i'==2 | p3_3_`i'==3 | p3_3_`i'==4 | p3_3_`i'==34 | p3_3_`i'==5 | p3_3_`i'==6 | p3_3_`i'==7 | p3_3_`i'==8 | p3_3_`i'==9 |
						p3_3_`i'==10 | p3_3_`i'==11 | p3_3_`i'==13 | (p3_3_`i'==14 & p3_2_`i'>2) | p3_3_`i'==15 | p3_3_`i'==97;
};

 ******************* INTEREST RATES *************************;
* Main residence;
forvalues i=1(1)4{;
*rename p2_9_`i' loantypemresid_`i' /* 1-mortgage, 2- othsecured, 3- personal, 4- credit line, 5- deferred, 6- advances, 7- friends family, 97- other, 98- don't know missing */;
rename p2_13_`i' loanratemresid_`i';
rename p2_14_`i' loanfixmresid_`i';
replace loanfixmresid_`i'=1 if loanfixmresid_`i'==22;
replace loanfixmresid_`i'=0 if loanfixmresid_`i'==11;
};

* Other properties (up to 3 additional properties and 3 loans for each one);
forvalues a=1(1)3{ /*property*/;
forvalues i=1(1)3{ /*loan*/;

*rename p2_52_`a'_`i' loantypeothprop_`a'_`i' /* 1-mortgage, 2- othsecured, 3- personal, 4- credit line, 5- deferred, 6- advances, 7- friends family, 97- other, 98- don't know missing */;
rename p2_56_`a'_`i' loanrateothprop_`a'_`i';
rename p2_57_`a'_`i' loanfixothprop_`a'_`i';
replace loanfixothprop_`a'_`i'=1 if loanfixothprop_`a'_`i'==22;
replace loanfixothprop_`a'_`i'=0 if loanfixothprop_`a'_`i'==11;
};
};

* Other loans;
foreach t in 1 2 3 4{;
*rename p3_2_`t' loantypeother_`t' /* 1-mortgage, 2- othsecured, 3- personal, 4- credit line, 5- deferred, 6- advances, 7- friends family, 97- other, 98- don't know missing */;
rename p3_7_`t' loanrateother_`t';
rename p3_8_`t' loanfixother_`t';
replace loanfixother_`t'=1 if loanfixother_`t'==22;
replace loanfixother_`t'=0 if loanfixother_`t'==11;
};


*************************** INTEREST RATES *******************************;
******* Housing ********;
gen int_housing=0;
forvalues i=1(1)4{;
replace int_housing=int_housing+loanratemresid_`i'*p2_12_`i' if p2_9_`i'<=2; 
};

forvalues a=1(1)3 {;
forvalues i=1(1)3 {;
replace int_housing=int_housing+loanrateothprop_`a'_`i'*p2_55_`a'_`i' if  p2_52_`a'_`i'<=2;
};
};

forvalues i=1(1)4{;
replace int_housing=int_housing+loanrateother_`i'*p3_6_`i' if p3_3_`i'==14 & p3_2_`i'<=2;
};
replace p2_55_4=0 if p2_55_4==.;
replace int_housing=int_housing/(vhousing-p2_55_4);

******** Business *******;
gen int_busloan=0;
forvalues i=1(1)4{;
replace int_busloan=int_busloan+loanrateother_`i'*p3_6_`i' if p3_3_`i'==12;
};

replace int_busloan=int_busloan/vbusloan;

********* Other *********;
gen int_restbis=0;
forvalues i=1(1)4{;
replace int_restbis=int_restbis+loanratemresid_`i'*p2_12_`i' if p2_9_`i'>2 & p2_9_`i'<=97; 
};

forvalues a=1(1)3 {;
forvalues i=1(1)3 {;
replace int_restbis=int_restbis+loanrateothprop_`a'_`i'*p2_55_`a'_`i' if  p2_52_`a'_`i'>2 & p2_52_`a'_`i'<=97;
};
};

forvalues i=1(1)4{;
replace int_restbis=int_restbis+loanrateother_`i'*p3_6_`i' if p3_3_`i'==1 | p3_3_`i'==2 | p3_3_`i'==3 | p3_3_`i'==4 | p3_3_`i'==34 | p3_3_`i'==5 | p3_3_`i'==6 | p3_3_`i'==7 | p3_3_`i'==8 | p3_3_`i'==9 |
						p3_3_`i'==10 | p3_3_`i'==11 | p3_3_`i'==13 | (p3_3_`i'==14 & p3_2_`i'>2) | p3_3_`i'==15 | p3_3_`i'==97;
};

replace int_restbis=int_restbis/vrestbis;



*************** Debt Portfolio Structure ***************;
/* Housing (debt 1), busloan (portfdebt2), Credcard (debt 3), Rest (debt 4)*/; 

gen credcard=0;
******* ONE DEBT ********************************************************************;
gen portfdebt1=0;
replace portfdebt1=1 if housing==1 & busloan==0 & credcard==0 & restbis==0;

gen portfdebt2=0;
replace portfdebt2=1 if housing==0 & busloan==1 & credcard==0 & restbis==0;

					
gen portfdebt3=0;
replace portfdebt3=1 if housing==0 & busloan==0 & credcard==1 & restbis==0;

gen portfdebt4=0;
replace portfdebt4=1 if housing==0 & busloan==0 & credcard==0 & restbis==1;


******* TWO DEBTS ********************************************************************;
gen portfdebt12=0;
replace portfdebt12=1 if housing==1 & busloan==1 & credcard==0 & restbis==0;

gen portfdebt13=0;
replace portfdebt13=1 if housing==1 & busloan==0 & credcard==1 & restbis==0;

gen portfdebt14=0;
replace portfdebt14=1  if housing==1 & busloan==0 & credcard==0 & restbis==1;

gen portfdebt23=0;
replace portfdebt23=1  if housing==0 & busloan==1 & credcard==1 & restbis==0;

gen portfdebt24=0;
replace portfdebt24=1  if housing==0 & busloan==1 & credcard==0 & restbis==1;


gen portfdebt34=0;
replace portfdebt34=1  if housing==0 & busloan==0 & credcard==1 & restbis==1;


**********THREE DEBTS ********************************************************************;
gen portfdebt123=0;
replace portfdebt123=1  if housing==1 & busloan==1 & credcard==1 & restbis==0;

gen portfdebt124=0;
replace portfdebt124=1  if housing==1 & busloan==1 & credcard==0 & restbis==1;

gen portfdebt134=0;
replace portfdebt134=1  if housing==1 & busloan==0 & credcard==1 & restbis==1;

gen portfdebt234=0;
replace portfdebt234=1  if housing==0 & busloan==1 & credcard==1 & restbis==1;

********* FOUR DEBTS *********************************************************************;
gen portfdebt1234=0;
replace portfdebt1234=1  if housing==1 & busloan==1 & credcard==1 & restbis==1;
*/;

*ALGUN TIPO DE DEUDA PENDIENTE;
*SOME TYPE OF OUTSTANDING DEBT;

*Para calcular la proporción de hogares que tienen algún tipo de deuda pendiente generamos una nueva variable;
*To obtain the percentage of households that have some type of outstanding debt we generate a new variable;

gen adeuda= (debtmresid==1| debtothprop==1| p3_1>0);
rename adeuda anydebt;
label var anydebt "have some type of outstanding debt";

*Para calcular el valor de las deudas pendientes generamos una nueva variable;
*To obtain the value of the outstanding debt we generate a new variable;

gen vdeuda= vdebtmresid + vdebtothprop+ vmortgoth+ vpersonal+ vothdebt;
rename vdeuda vdebt;
label var vdebt "value of the outstanding debt";


foreach var in portfdebt1 portfdebt2 portfdebt3 portfdebt4 portfdebt12 portfdebt13 portfdebt14 portfdebt23 
 portfdebt24 portfdebt34 portfdebt123 portfdebt124 portfdebt134 portfdebt234 portfdebt1234 {;
 
 gen v`var'=.;
 replace v`var'=vdebt if `var'==1;
 
 };

 


*VARIABLES DE RIQUEZA TOTAL Y RIQUEZAS INTERMEDIAS;
*TOTAL AND INTERMEDIATE WEALTH VARIABLES;


*ACTIVOS REALES;
*REAL ASSETS;

gen actreales=0;
replace actreales=actreales+vmresid if (vmresid>0 & vmresid~=.);
replace actreales=actreales+vothprop;
replace actreales=actreales+vjewel if (vjewel>0 & vjewel~=.);
replace actreales=actreales+valhog;

rename actreales rassets;
label var rassets "Value of real assets";

*ACTIVOS FINANCIEROS;
*FINANCIAL ASSETS;

gen actfinanc=0;
replace actfinanc=actfinanc+vaccount_pay if (vaccount_pay>0 & vaccount_pay~=.);
replace actfinanc=actfinanc+vlistshare if (vlistshare>0 & vlistshare~=.);
replace actfinanc=actfinanc+vunlist if (vunlist>0 & vunlist~=.);
replace actfinanc=actfinanc+vfixsec if (vfixsec>0 & vfixsec~=.);
replace actfinanc=actfinanc+allf if (allf>0 & allf~=.);
replace actfinanc=actfinanc+vaccount_nopay;
replace actfinanc=actfinanc+vpenplan;
replace actfinanc=actfinanc+vlifeinsur;
replace actfinanc=actfinanc+vcreditor;

rename actfinanc fassets;
label var fassets "Value of financial assets";

*RIQUEZA BRUTA;
*GROSS WEALTH;

gen riquezabr=0;
replace riquezabr=riquezabr+rassets+fassets;

rename riquezabr gwealth;
label var gwealth "Gross Wealth";

*RIQUEZA NETA=RIQUEZA BRUTA-DEUDAS;
*NET WEALTH=GROSS WEALTH-DEBTS;

gen riquezanet=gwealth-vdebt;
rename riquezanet nwealth;
label var nwealth "Net Wealth";

*CUADRO 6: VALOR TIPOS DE DEUDA SEGUN OBJETIVO DE LA DEUDA;
*TABLE 6: VALUE OF DEBTS BY PURPOSE OF DEBTS;

*TBD;

*Para deuda por compra vivienda principal usamos dvivpral;
*For debt originated by home purchase we use dvivpral;

*Para deuda por compra otras prop. inmobiliarias usamos deuoprop;
*For debt originated by purchase of other real estate properties we use deuoprop;

*Para deudas pendientes por el resto de deudas (garantia real, credito personal, otras deudas, deudas con tarjetas de credito) usaremos deuotros;
*For other outstanding debts (secured loans, personal loans, credit card balances and other debts) we use deuotros;

*CUADRO 8: RATIOS INDIVIDUALES DE DEUDA;
*TABLE 8: INDIVIDUAL DEBT RATIOS;

*PAGOS POR DEUDAS;
*DEBT PAYMENTS;

*Para el total de pagos por deudas generamos la variable pagodeuda;
*For total debt payments we generate the variable pagodeuda;

gen pagodeuda=0;
gen pagodeuviv=0;
gen pagodeuoprop=0;
gen pagodeusec3=0;


set output error;
forvalues j=1/4 {;

	display _newline(1) `j';

	gen np2_18_`j'=p2_18_`j';
	replace np2_18_`j'=0 if (p2_18_`j'==.|p2_18_`j'<0);
	replace pagodeuviv=pagodeuviv+np2_18_`j';
	};

forvalues j=1/4 { ;
	
	display _newline(1) `j';
	gen np3_11_`j'=p3_11_`j';
	replace np3_11_`j'=0 if (p3_11_`j'==.|p3_11_`j'<0);
	replace pagodeusec3=pagodeusec3+np3_11_`j';	
	};

forvalues m=1/3   {;

	forvalues j=1/3 {;

	display _newline(1) `m' `j';
	
	gen np2_61_`m'_`j'=p2_61_`m'_`j';
	replace np2_61_`m'_`j'=0 if (p2_61_`m'_`j'==.|p2_61_`m'_`j'<0);
	replace pagodeuoprop=pagodeuoprop+np2_61_`m'_`j';
	};

};
set output proc;

gen np2_61_4=p2_61_4;
replace np2_61_4=0 if (p2_61_4==. | p2_61_4<0);
replace pagodeuoprop=pagodeuoprop+np2_61_4;




replace pagodeuda=pagodeuviv+pagodeuoprop+pagodeusec3;

rename pagodeuda paydebt;
label var paydebt "Monthly total debt payments";
rename pagodeuviv paydresid;
label var paydresid "Monthly residential debt payments";
rename pagodeuoprop payothprop;
label var payothprop "Monthly other properties debt payments";
rename pagodeusec3 paypersonal;
label var paypersonal "Monthly personal debt payments";

*CUADRO 9: GASTO EN BIENES DURADEROS Y NO DURADEROS Y TENENCIA DE BIENES DURADEROS;
*TABLE 9: EXPENDITURE ON NON-DURABLE AND DURABLE GOODS AND HOLDINGS OF DURABLE GOODS;

*1.-GASTO ANUAL BIENES VARIOS (% y mediana);
*1.-ANNUAL EXPENDITURE ON DIFFERENT GOODS (% and median);

*Gasto anual en Alimentacion;
*Annual expenditure on Food;

gen frec=12 if p9_2b==2;
replace frec=12*4.3 if p9_2b==1;
gen alim=0;
replace alim=alim+(p9_2*frec) if p9_2>0;
rename alim food;
label var food "Annual expenditure on Food";

*Gasto anual en Otros bienes no duraderos;
*Annual expenditure on Other non-durable goods;

gen nodur=0;
replace nodur=nodur+ (p9_1*12)-food if p9_1>0;
label var nodur "Annual expenditure on Other non-durable goods";

*Gasto anual en vehiculos (si/no y valor);
*Annual expenditure on vehicles (yes/no and value);

*Para decisión adquisición vehículos;
*For the decision to buy vehicles;

gen gvehic=(p2_73==1 | p2_77==1);
rename gvehic vehic;
label var vehic "household purchased a vehicle that year";

*Para valor adquisicion vehículos;
*For the value of vehicles purchased;

gen gimpvehic=0;
replace gimpvehic=gimpvehic+p2_74 if (p2_74>0 & p2_74~=.);
replace gimpvehic=gimpvehic+p2_78 if (p2_78>0 & p2_78~=.);
rename gimpvehic vvehicle;
label var vvehicle "value of vehicles purchased";

*Gasto anual en Otros bienes duraderos (si/no y valor);
*Annual expenditure on Other durable goods (yes/no and value);


*Para decisión adquisición bienes duraderos utilizamos la p2_69;
*For the decision to buy durable goods we use the variable p2_69;

*Para valor adquisicion bienes duraderos usamos p2_70;
*For the value of durable goods purchases we use p2_70;


*2.- PARA TENENCIA DURADEROS (% Y MEDIANA);
*2.- FOR HOLDINGS OF DURABLE GOODS (% AND MEDIAN);

*Tenencia vehiculos;
*Holding of vehicles;

*Proporcion con vehiculos;
*Percentage with vehicles;

gen tvehic=(p2_72>0|p2_76>0);

*Mediana para los que tienen;
*Median for the ones who have; 

gen timpvehic=0;
replace timpvehic = timpvehic + p2_75 if (p2_72>0 & p2_75>0 & p2_75~=.);
replace timpvehic = timpvehic + p2_79 if ( p2_76>0 &  p2_79>0 & p2_79~=.);

*Tenencia Otros bienes duraderos;
*Holding of Other durable goods;

*Para valor tenencia bienes duraderos usamos p2_71;
*For the value of durable goods holdings we use p2_71;


*VARIABLES DE CARACTERISTICAS DE LOS HOGARES QUE FIGURAN EN LOS CUADROS;
*VARIABLES OF HOUSEHOLD CHARACTERISTICS THAT APPEAR IN THE TABLES;

*1.- DEFINICIÓN DE PERCENTILES (i) RENTA TOTAL HOGAR Y (ii) RIQUEZA NETA;
*1.- DEFINITION OF PERCENTILES (i) HOUSEHOLD TOTAL INCOME AND (ii) NET WEALTH; 
rename renthog hhincome /* annual 2001 for 2002 wave, 2004 (2005 wave), 2007 (2008 wave) */;
_pctile hhincome [pweight=facine3], p(20,40,60,80,90);
return list;

gen percrent=1 if (hhincome<r(r1));
replace percrent=2 if (hhincome>=r(r1) & hhincome<r(r2));
replace percrent=3 if (hhincome>=r(r2) & hhincome<r(r3));
replace percrent=4 if (hhincome>=r(r3) & hhincome<r(r4));
replace percrent=5 if (hhincome>=r(r4) & hhincome<r(r5));
replace percrent=6 if  hhincome>=r(r5);


_pctile nwealth [pweight=facine3], p(25,50,75,90);
return list;

gen percriq=1 if (nwealth<r(r1));
replace percriq=2 if (nwealth>=r(r1) & nwealth<r(r2));
replace percriq=3 if (nwealth>=r(r2) & nwealth<r(r3));
replace percriq=4 if (nwealth>=r(r3) & nwealth<r(r4));
replace percriq=5 if  nwealth>=r(r4);

gen percriq25=1 if nwealth==r(r1);
gen percriq50=1 if nwealth==r(r2);
gen percriq75=1 if nwealth==r(r3);



*2.- NOMBRE Y CODIFICACIÓN DE LAS VARIABLES QUE RECOGEN CARACTERÍSTICAS SOCIO-DEMOGRÁFICAS DEL HOGAR QUE APARECEN EN LOS CUADROS;
*2.- NAME AND CODING OF THE VARIABLES THAT CONTAIN HOUSEHOLDS SOCIO-DEMOGRAPHIC CHARACTERISTICS THAT APPEAR IN THE TABLES;

*EDAD DEL CABEZA DE FAMILIA;
*AGE OF HOUSEHOLD HEAD;
*bage: toma valores 1 a 6, <35, >34 & <45, >44 & <55, >54 & <65, >64 & <75, >74;
*bage: takes values 1 to 6, <35, >34 & <45, >44 & <55, >54 & <65, >64 & <75, >74;

*SITUACION LABORAL DEL CABEZA DE FAMILIA;
*LABOUR MARKET SITUATION OF HOUSEHOLD HEAD;
*nsitlabdom: toma valores 1 a 4, empleado por cuenta ajena, empleado por cuenta propia, jubilado, otro tipo de inactivo o parado;
*nsitlabdom: takes values 1 to 4, employee, self-employed, retired, other type of economic inactivity or unemployed;

*NIVEL DE EDUCACION DEL CABEZA DE FAMILIA;
*LEVEL OF EDUCATION OF HOUSEHOLD HEAD;
*neducdom: toma valores 1 a 3, inferior a bachillerato, bachillerato, estudios universitarios;
*neducdom: takes values 1 to 3, below secondary education, secondary education, University education;

*REGIMEN DE TENENCIA DE LA VIVIENDA PRINCIPAL;
*STATUS OF MAIN RESIDENCE;
*np2_1: toma valores 1 y 0, propiedad, otros regímenes de tenencia;
*np2_1: takes values 1 and 0, ownership, other;


*NUMERO DE ADULTOS EN EL HOGAR TRABAJANDO;
*NUMBER OF ADULT HOUSEHOLD MEMBERS WORKING;
*nnumadtrab: toma valores 0 a 3, ninguno, uno, dos, tres o más;
*nnumadtrab: takes values 0 to 3, none, one, two, three or more;


*NUMERO DE MIEMBROS EN EL HOGAR;
*NUMBER OF HOUSEHOLD MEMBERS;
*np1: toma valores 1 a 5, uno, dos, tres, cuatro, cinco o más.
*np1: takes values 1 to 5, one, two, three, four, five or more.


**** Reference person (designed by the household) variables ****;
/* From questionnaire: "The reference person is the person, or one of the persons, responsible for the accommodation. It will normally be the person in the 
household who chiefly deals with the financial issues." */;

rename p1 members /* Number of household members */;




forvalues i = 1(1)9 {;
	rename p1_1_`i' sex`i' /* Male (1), Female (0)*/;
	replace sex`i'=0 if sex`i'==2;
	rename p1_2b_`i' nac`i';
	rename p1_3_`i' relref`i';
	rename p1_5_`i' educ`i' /* Education level (see questionnaire)*/;
	rename p1_7_`i' health`i' /* Health status of reference person: 1-very good, 2-good, 3-acceptable, 4-poor, 5-very poor */;
	rename p6_1c1_`i' employee`i';
	rename p6_1c2_`i' selfemployed`i';
	rename p6_1c3_`i' unemployed`i';
	rename p6_1c4_`i' retiree`i';
	rename p6_1c5_`i' disable`i';
	rename p6_1c6_`i' student`i';
	rename p6_1c7_`i' housew`i';
	rename p6_1c8_`i' oth_inact`i';
	rename p6_4_`i' typejob`i';
	gen bankjob`i'=0;
	replace bankjob`i'=1 if typejob`i'==9;
	};

	forvalues i = 1(1)9 {;
	gen ageaux`i'=0;
	replace ageaux`i'=2005-nac`i';
	gen child`i'=0;
	replace child`i'=1 if ageaux`i'<16 ;
	};

cap drop ageaux*;

egen nchilds=rowtotal(child1-child9);
	
gen sex=0;
gen nac=0;
gen educ=0;
gen health=0;
gen employee=0;
gen selfemployed=0;
gen unemployed=0;
gen retiree=0;
gen disable=0;
gen student=0;
gen housew=0;
gen oth_inact=0;
gen bankjob=0;

* Dummy variable for university degree;
* Ordinary university degree / Training leading to an officially recognised professional specialisation;
* Postgraduate university education ;

forvalues i = 1(1)9 {;
gen univ`i'=0;
replace univ`i'=1 if educ`i'==10 | educ`i'==11 | educ`i'==12;

gen leveleduc`i'="primary";
replace leveleduc`i'="lowsec" if educ`i'==4 | educ`i'==5;
replace leveleduc`i'="highsec" if educ`i'==6 | educ`i'==7 | educ`i'==8;
replace leveleduc`i'="univ" if educ`i'==9 | educ`i'==10 | educ`i'==11 | educ`i'==12;
};

gen univ=0;
gen leveleduc="";


/* Marital status reference person: married if any other person in the household declares to be the couple of the head */;

gen married=0;

forvalues i = 2(1)9 {;
	replace married=1 if relref`i'==2;
	};

gen couplewith=(married==1 & nchilds>0);
gen couplewithout=(married==1 & nchilds==0);
gen singlewith=(married==0 & nchilds>0);
gen singlewithout=(married==0 & nchilds==0);	
	
rename p1_4_1 marital1 /* Marital status reference person: 1-single, 2-married, 3-de facto partner 
						4-separated, 5-divorced, 6-widowed */;

/* With the information of the other members, create variables that summarize the familiar characteristics */;

*gen othcoup=0 /* to identify those hh where household head is not the reference person in the survey */;

*CRITERIUM: Take the main earner in employees. Otherwise, take the male;

* Compute wage for each member of the houysehold;
forvalues i=1(1)9{;
replace student`i'=0 if oth_inact`i'==1 | disable`i'==1 | housew`i'==1 | unemployed`i'==1 | retiree`i'==1 | selfemployed`i'==1 | employee`i'==1;
replace oth_inact`i'=0 if disable`i'==1 | housew`i'==1 | unemployed`i'==1 | retiree`i'==1 | selfemployed`i'==1 | employee`i'==1;
replace disable`i'=0 if housew`i'==1 | unemployed`i'==1 | retiree`i'==1 | selfemployed`i'==1 | employee`i'==1;
replace housew`i'=0 if unemployed`i'==1 | retiree`i'==1 | selfemployed`i'==1 | employee`i'==1;
replace unemployed`i'=0 if retiree`i'==1 | selfemployed`i'==1 | employee`i'==1;
replace retiree`i'=0 if selfemployed`i'==1 | employee`i'==1;
replace selfemployed`i'=0 if employee`i'==1;
gen ageaux`i'=0;
replace ageaux`i'=2005-nac`i';
replace retiree`i'=1 if (housew`i'==1 | oth_inact`i'==1 | disable`i'==1 | student`i'==1) & ageaux`i'>=65 /* Take this persons as retired */;
replace housew`i'=0 if retiree`i'==1;
replace oth_inact`i'=0 if retiree`i'==1;
replace disable`i'=0 if retiree`i'==1;
replace student`i'=0 if retiree`i'==1;
};

forvalues i=1(1)9{;
	egen wage`i'=rowtotal(p6_14_`i'_*);
	gen mainearner`i'=0;
		replace employee`i'=1 if wage`i'>0 & student`i'==0 & oth_inact`i'==0 & disable`i'==0 & housew`i'==0 & 
	unemployed`i'==0 & retiree`i'==0 & selfemployed`i'==0 & employee`i'==0;
	};
	
replace mainearner1=1;

forvalues i=2(1)9{;
	replace mainearner`i'=1 if wage`i'>wage1 & relref`i'==2 & employee`i'==1;
	replace mainearner1=0   if wage`i'>wage1 & relref`i'==2 & employee`i'==1;	
	};	

forvalues i =2(1)9 {;
	gen othcoup`i'=0;
	replace othcoup`i'=1 if married==1 & sex1==0 & sex`i'==1 & relref`i'==2;	
	replace othcoup`i'=1 if married==1 & mainearner`i'==1 & relref`i'==2;
	replace othcoup`i'=1 if married==1 & (housew==1 | student==1) & 
		(unemployed`i'==1 | retiree`i'==1 | selfemployed`i'==1) & relref`i'==2 /*Take the couple when head is housewife */;
	replace sex=sex`i' if othcoup`i'==1;
	replace nac=nac`i' if othcoup`i'==1;
	replace educ=educ`i' if othcoup`i'==1;
	replace health=health`i' if othcoup`i'==1;
	replace employee=employee`i' if othcoup`i'==1;
	replace selfemployed=selfemployed`i' if othcoup`i'==1;
	replace unemployed=unemployed`i' if othcoup`i'==1;
	replace student=student`i' if othcoup`i'==1;
	replace housew=housew`i' if othcoup`i'==1;
	replace oth_inact=oth_inact`i' if othcoup`i'==1;
	replace retiree=retiree`i' if othcoup`i'==1;
	replace health=health`i' if othcoup`i'==1;
	replace univ=univ`i' if othcoup`i'==1;
	replace leveleduc=leveleduc`i' if othcoup`i'==1;
	replace bankjob=bankjob`i' if othcoup`i'==1;
	};

egen othcoup=rowtotal(othcoup*);

replace sex=sex1 if othcoup==0;
replace nac=nac1 if othcoup==0;
replace educ=educ1 if othcoup==0;
replace health=health1 if othcoup==0;
replace employee=employee1 if othcoup==0;
replace selfemployed=selfemployed1 if othcoup==0;
replace retiree=retiree1 if othcoup==0;
replace disable=disable1 if othcoup==0;
replace student=student1 if othcoup==0;
replace housew=housew1 if othcoup==0;
replace oth_inact=oth_inact1 if othcoup==0;
replace unemployed=unemployed1 if othcoup==0;
replace univ=univ1 if othcoup==0;
replace leveleduc=leveleduc1 if othcoup==0;
replace bankjob=bankjob1 if othcoup==0;


/* Gen dummy to identify status of the couple */;
gen pemployee=0;
gen pselfemployed=0;
gen punemployed=0;
gen pretiree=0;
gen pdisable=0;
gen pstudent=0;
gen phousew=0;
gen poth_inact=0;
gen puniv=0;
gen pnac=0;

forvalues i=2(1)9 {;
	replace punemployed=1 if othcoup`i'==0 & unemployed`i'==1 & relref`i'==2;
	replace pemployee=1 if othcoup`i'==0 & employee`i'==1 & relref`i'==2;
	replace pretiree=1 if othcoup`i'==0 & retiree`i'==1 & relref`i'==2;
	replace pselfemployed=1 if othcoup`i'==0 & selfemployed`i'==1 & relref`i'==2;
	replace pdisable=1 if othcoup`i'==0 & disable`i'==1 & relref`i'==2;
	replace pstudent=1 if othcoup`i'==0 & student`i'==1 & relref`i'==2;
	replace phousew=1 if othcoup`i'==0 & housew`i'==1 & relref`i'==2;
	replace poth_inact=1 if othcoup`i'==0 & oth_inact`i'==1 & relref`i'==2;
	replace puniv=1 if othcoup`i'==0 & univ`i'==1 & relref`i'==2;
	replace pnac=1 if othcoup`i'==0 & nac`i'==1 & relref`i'==2;

	replace punemployed=1 if othcoup`i'==1 & unemployed1==1 & relref`i'==2;
	replace pemployee=1 if othcoup`i'==1 & employee1==1 & relref`i'==2;
	replace pretiree=1 if othcoup`i'==1 & retiree1==1 & relref`i'==2;
	replace pselfemployed=1 if othcoup`i'==1 & selfemployed1==1 & relref`i'==2;
	replace pdisable=1 if othcoup`i'==1 & disable1==1 & relref`i'==2;
	replace pstudent=1 if othcoup`i'==1 & student1==1 & relref`i'==2;
	replace phousew=1 if othcoup`i'==1 & housew1==1 & relref`i'==2;
	replace poth_inact=1 if othcoup`i'==1 & oth_inact1==1 & relref`i'==2;
	replace puniv=1 if othcoup`i'==1 & univ1==1 & relref`i'==2;
	replace pnac=1 if othcoup`i'==1 & nac1==1 & relref`i'==2;
	};
* Define other reference person for housew/student households: specifically, take as reference person those sons or daughters that are
main earners;

egen maxw=rowmax(wage1 wage2 wage3 wage4 wage5 wage6 wage7 wage8 wage9);

forvalues i=2(1)9{;
		gen oth_member`i'=0;
		replace oth_member`i'=1 if (housew==1 | student==1) & wage`i'==maxw & maxw>0;
		replace employee`i'=1 if oth_member`i'==1;
		replace sex=sex`i' if oth_member`i'==1;
		*replace psex=0 if oth_member`i'==1 /* Assume has no couple */;
		replace nac=nac`i' if oth_member`i'==1;
		replace pnac=0 if oth_member`i'==1 /* Assume has no couple */;
		replace educ=educ`i' if oth_member`i'==1;
		*replace peduc=0 if oth_member`i'==1 /* Assume has no couple */;
		replace health=health`i' if oth_member`i'==1;
		*replace phealth=0 if oth_member`i'==1 /* Assume has no couple */;
		replace employee=employee`i' if oth_member`i'==1;
		replace pemployee=0 if oth_member`i'==1 /* Assume has no couple */;
		replace selfemployed=selfemployed`i' if oth_member`i'==1;
		replace pselfemployed=0 if oth_member`i'==1 /* Assume has no couple */;
		replace retiree=retiree`i' if oth_member`i'==1;
		replace pretiree=0 if oth_member`i'==1 /* Assume has no couple */;
		replace disable=disable`i' if oth_member`i'==1;
		replace pdisable=0 if oth_member`i'==1 /* Assume has no couple */;
		replace student=student`i' if oth_member`i'==1;
		replace pstudent=0 if oth_member`i'==1 /* Assume has no couple */;
		replace housew=housew`i' if oth_member`i'==1;
		replace phousew=0 if oth_member`i'==1 /* Assume has no couple */;
		replace oth_inact=oth_inact`i' if oth_member`i'==1;
		replace poth_inact=0 if oth_member`i'==1 /* Assume has no couple */;
		replace unemployed=unemployed`i' if oth_member`i'==1;
		replace punemployed=0 if oth_member`i'==1 /* Assume has no couple */;
		replace univ=univ`i' if oth_member`i'==1;
		replace leveleduc=leveleduc`i' if oth_member`i'==1;
		replace puniv=0 if oth_member`i'==1 /* Assume has no couple */;
		};	

egen auxoth=rowtotal(oth_member*);
		
/* Choose other household member if there are no employees*/;
forvalues i=2(1)9{;
		gen oth2_member`i'=0;
		replace oth2_member`i'=1 if (housew==1 | student==1) & auxoth==0 & selfemployed`i'==1;
		replace selfemployed`i'=1 if oth2_member`i'==1;
		replace sex=sex`i' if oth2_member`i'==1;
		*replace psex=0 if oth_member`i'==1 /* Assume has no couple */;
		replace nac=nac`i' if oth2_member`i'==1;
		replace pnac=0 if oth2_member`i'==1 /* Assume has no couple */;
		replace educ=educ`i' if oth2_member`i'==1;
		*replace peduc=0 if oth_member`i'==1 /* Assume has no couple */;
		replace health=health`i' if oth2_member`i'==1;
		*replace phealth=0 if oth_member`i'==1 /* Assume has no couple */;
		replace employee=employee`i' if oth2_member`i'==1;
		replace pemployee=0 if oth2_member`i'==1 /* Assume has no couple */;
		replace selfemployed=selfemployed`i' if oth2_member`i'==1;
		replace pselfemployed=0 if oth2_member`i'==1 /* Assume has no couple */;
		replace retiree=retiree`i' if oth2_member`i'==1;
		replace pretiree=0 if oth2_member`i'==1 /* Assume has no couple */;
		replace disable=disable`i' if oth2_member`i'==1;
		replace pdisable=0 if oth2_member`i'==1 /* Assume has no couple */;
		replace student=student`i' if oth2_member`i'==1;
		replace pstudent=0 if oth2_member`i'==1 /* Assume has no couple */;
		replace housew=housew`i' if oth2_member`i'==1;
		replace phousew=0 if oth2_member`i'==1 /* Assume has no couple */;
		replace oth_inact=oth_inact`i' if oth2_member`i'==1;
		replace poth_inact=0 if oth2_member`i'==1 /* Assume has no couple */;
		replace unemployed=unemployed`i' if oth2_member`i'==1;
		replace punemployed=0 if oth2_member`i'==1 /* Assume has no couple */;
		replace univ=univ`i' if oth2_member`i'==1;
		replace puniv=0 if oth2_member`i'==1 /* Assume has no couple */;
		replace leveleduc=leveleduc`i' if oth2_member`i'==1;
		};
		
gen bhealth=0;
replace bhealth=1 if health>=4;

egen auxoth2=rowtotal(oth2_member*);

egen aux=rowtotal(employee selfemployed unemployed retiree disable student housew oth_inact);
keep if aux==1;
gen age=2005-nac;
replace age=age/10;

** Age dummies **;
gen age1=0;
replace age1=1 if age>=3 & age<3.5;

gen age2=0;
replace age2=1 if age>=3.5 & age<4;

gen age3=0;
replace age3=1 if age>=4 & age<4.5;

gen age4=0;
replace age4=1 if age>=4.5 & age<5;

gen age5=0;
replace age5=1 if age>=5 & age<5.5;

gen age6=0;
replace age6=1 if age>=5.5 & age<6;

gen age7=0;
replace age7=1 if age>=6 & age<6.5;

gen age8=0;
replace age8=1 if age>=6.5 & age<7;

gen age9=0;
replace age9=1 if age>=7 & age<7.6;

gen age_inst=0;
replace age_inst=1 if age1==1;
replace age_inst=2 if age2==1;
replace age_inst=3 if age3==1;
replace age_inst=4 if age4==1;
replace age_inst=5 if age5==1;
replace age_inst=6 if age6==1;
replace age_inst=7 if age7==1;
replace age_inst=8 if age8==1;
replace age_inst=9 if age9==1;


gen agesq=age^2;

gen page=2005-nac;
replace page=page/10;

** page dummies **;
gen page1=0;
replace page1=1 if page>=3 & page<3.5;

gen page2=0;
replace page2=1 if page>=3.5 & page<4;

gen page3=0;
replace page3=1 if page>=4 & page<4.5;

gen page4=0;
replace page4=1 if page>=4.5 & page<5;

gen page5=0;
replace page5=1 if page>=5 & page<5.5;

gen page6=0;
replace page6=1 if page>=5.5 & page<6;

gen page7=0;
replace page7=1 if page>=6 & page<6.5;

gen page8=0;
replace page8=1 if page>=6.5 & page<7;

gen page9=0;
replace page9=1 if page>=7 & page<7.6;

gen page_inst=0;
replace page_inst=1 if page1==1;
replace page_inst=2 if page2==1;
replace page_inst=3 if page3==1;
replace page_inst=4 if page4==1;
replace page_inst=5 if page5==1;
replace page_inst=6 if page6==1;
replace page_inst=7 if page7==1;
replace page_inst=8 if page8==1;
replace page_inst=9 if page9==1;

gen pagesq=page^2;


/* Drop multiple-unrelated households */;

egen minval=rowmin(relref*);
replace minval=0 if minval==.;

gen madult=0;
replace madult=1 if minval==9 & (year==2002 | year==2005);
replace madult=1 if minval==12 & (year==2008 | year==2011);

  
		  ******************* Application for loans ********************;

rename p3_14 nreject /* number of applications rejected */;

/* Totally reject loan application (any) */;
gen reject=0;
replace reject=1 if nreject>0;
replace reject=0 if nreject==.;

forvalues i=1(1)5 {;
	rename p3_13s`i' rnoappl`i' /* Reasons of not applying for a loan */;
	rename p3_15s`i' rreject`i' /* Reasons of rejecting */;
	};

rename p3_12 napplic /* Number of no applications made in last two years */;

/* Discouraged borrowers: refuse to apply for a loan because it would be turned down (any member of the household. Exclude debt holders */;
gen discour=0;
replace discour=1 if (rnoappl1==4 | rnoappl2==4 | rnoappl3==4 | rnoappl4==4 | rnoappl5==4) & anydebt==0 & napplic==0;


/* Applicant: whether the household made any loan application or refused beacuse of sure rejecting */;
gen applic=0;
replace applic=1 if napplic>0 | discour==1 | anydebt==1;
* replace applic=0 if ration==0 & anydebt==0 /* Applied, accepted but did not take the loan (we think they took the loan and repaid the debt) */;

* gen applic_non_disc=0;
* replace applic_non_disc=1 if napplic>0 | anydebt==1;


rename p3_16 npartrej /* # times granted smaller amount than asked for */;



/* Partially rejected loan application (any) */;
gen partrej=0;
replace partrej=1 if npartrej>0;
replace partrej=0 if npartrej==.;

gen totpartrej=0;
replace totpartrej=1 if (reject==1 | partrej==1);
replace totpartrej=1 if discour==1;
*replace totpartrej=0 if anydebt==1;

/* Rationed: discouraged or reject totally or partially */;
gen ration2=0;
replace ration2=1 if discour==1 | partrej==1 | reject==1;
replace ration2=0 if ration2==.;
*replace ration2=0 if anydebt==1;

/* Rationed: discouraged or totally rejected */;
gen ration=0;
replace ration=1 if discour==1 | reject==1;
replace ration=0 if ration==.;
*replace ration=0 if anydebt==1;

*replace anydebt=1 if applic==1 & anydebt==0 & ration==0 /* Applied, borrowed and repaid, and report zero borrowing */;


/* Another definition is made 200 lines or more in advanced (guess that it was done in Venice)
/* Partially and Totally rationed */;

gen totpartrej=0;
replace totpartrej=1 if reject==1 | partrej==1;
*/;



**************** INCOME *********************;
replace hhincome=hhincome/acpi*100;
gen lincome=log(1+hhincome);
replace hhincome=hhincome/10000;
gen hhincomesq=(hhincome^2)/10000;

rename mrenthog mhhincome /* month oct2002 - may2003 (2002), nov2005 - may2006 (2005), nov2008 - jun2009 (2008) */;
replace mhhincome=mhhincome/mcpi*100;
replace paydebt=paydebt/mcpi*100;
gen mhhincomesq=mhhincome^2;

************* Debt to income ratio *************;
gen debt_income=paydebt/mhhincome;

************* Debt to income ratio (include rent) *************;
replace pay_rent=0 if pay_rent==.;
gen debt_rent_income=(paydebt+pay_rent)/mhhincome;

************** FINANCIAL HELP FROM RELATIVES AND FRIENDS *******************;
/*monetary assistance from friends or family members outside the
household, or from a partner no longer living in the household*/;

rename p6_59 finhelp;
replace finhelp=0 if finhelp==2;

rename p6_60 amounthelp;
replace amounthelp=amounthelp/mcpi*100;

************ ARREARS *****************;

/* In the last twelve months have you had any financial
difficulties which resulted in your delaying the payment of any of
your debts? */;

gen arrears=0;
replace arrears=1 if p9_16==1;

*replace anydebt=1 if arrears==1;
replace applic=1 if anydebt==1;
*replace ration=0 if arrears==1;
replace discour=0 if anydebt==1;

gen applic_non_disc=0;
replace applic_non_disc=1 if applic==1 & discour==0;

gen repay=.;
replace repay=1 if arrears==0 & anydebt==1;
replace repay=0 if arrears==1;

* Risk Aversion;
rename p9_11 riskaver;

gen risklot=.;
replace risklot=0 if riskaver==2 | riskaver==3 | riskaver==4;
replace risklot=1 if riskaver==1;

gen riskfair=.;
replace riskfair=0 if riskaver==1 | riskaver==3 | riskaver==4;
replace riskfair=1 if riskaver==2;

gen risksome=.;
replace risksome=0 if riskaver==1 | riskaver==2 | riskaver==4;
replace risksome=1 if riskaver==3;

gen norisk=.;
replace norisk=0 if riskaver==1 | riskaver==2 | riskaver==3;
replace norisk=1 if riskaver==4;

******** Dummies for hhincome ********;
_pctile hhincome, p(20,40,60,80);
scalar r1=r(r1);
scalar r2=r(r2);
scalar r3=r(r3);
scalar r4=r(r4);

gen hhincome1=0;
replace hhincome1=1 if hhincome<scalar(r1);

gen hhincome2=0;
replace hhincome2=1 if hhincome>=scalar(r1) & hhincome<scalar(r2);

gen hhincome3=0;
replace hhincome3=1 if hhincome>=scalar(r2) & hhincome<scalar(r3);

gen hhincome4=0;
replace hhincome4=1 if hhincome>=scalar(r3)  & hhincome<scalar(r4);

gen hhincome5=0;
replace hhincome5=1 if hhincome>scalar(r4);

gen inc_inst=0;
replace inc_inst=1 if hhincome1==1;
replace inc_inst=2 if hhincome2==1;
replace inc_inst=3 if hhincome3==1;
replace inc_inst=4 if hhincome4==1;

*********** Dummies for income II ************;
replace hhincome=hhincome*10000;

gen hh1=0;
replace hh1=1 if hhincome<=15000;
gen hh2=0;
replace hh2=1 if hhincome>15000 & hhincome<=25000;
gen hh3=0;
replace hh3=1 if hhincome>25000 & hhincome<=35000;
gen hh4=0;
replace hh4=1 if hhincome>35000 & hhincome<=45000;
gen hh5=0;
replace hh5=1 if hhincome>45000 & hhincome<=57000;
gen hh6=0;
replace hh6=1 if hhincome>57000;

*/;
gen hh_inst=0;
replace hh_inst=1 if hh1==1;
replace hh_inst=2 if hh2==1;
replace hh_inst=3 if hh3==1;
replace hh_inst=4 if hh4==1;
replace hh_inst=5 if hh5==1;
replace hh_inst=6 if hh6==1;
*replace hh_inst=7 if hh7==1;
*replace hh_inst=8 if hh8==1;
*replace hh_inst=9 if hh9==1;



replace hhincome=hhincome/10000;



*********** Dummies for nwealth ************;

replace nwealth=nwealth/acpi*100;
gen lnwealth=.;
replace lnwealth=log(1+abs(nwealth)) if nwealth>=0;
replace lnwealth=-log(1+abs(nwealth)) if nwealth<0;

gen nw1=0;
replace nw1=1 if nwealth<=10000;
gen nw2=0;
replace nw2=1 if nwealth>10000 & nwealth<=80000;
gen nw3=0;
replace nw3=1 if nwealth>80000 & nwealth<=200000;
gen nw4=0;
replace nw4=1 if nwealth>200000 & nwealth<=500000;
gen nw5=0;
replace nw5=1 if nwealth>500000;


***** Generate alternative wealth variables *****;
gen housewealth= nwealth;
replace housewealth=housewealth-vmresid/acpi*100+vdebtmresid/acpi*100 if debtmresid==1;

replace housewealth=housewealth + vdebtprop1/acpi*100 - p2_39_1*(p2_37_1/100)/acpi*100 if vdebtprop1>0;
replace housewealth=housewealth + vdebtprop2/acpi*100 - p2_39_2*(p2_37_1/100)/acpi*100 if vdebtprop2>0;
replace housewealth=housewealth + vdebtprop3/acpi*100 - p2_39_3*(p2_37_1/100)/acpi*100 if vdebtprop3>0;
replace housewealth=housewealth + vdebtprop4/acpi*100 - p2_39_4*(p2_37_1/100)/acpi*100 if vdebtprop4>0;

gen lhousingw=.;
replace lhousingw=log(1+abs(housewealth)) if housewealth>=0;
replace lhousingw=-log(1+abs(housewealth)) if housewealth<0;

gen buswealth=nwealth;
replace buswealth=buswealth-valhog/acpi*100+vbusloan;

gen lbusloanw=.;
replace lbusloanw=log(1+abs(buswealth)) if buswealth>=0;
replace lbusloanw=-log(1+abs(buswealth)) if buswealth<0;


gen otherwealth=nwealth;
replace otherwealth=otherwealth-vrestbis;

gen lrestbisw=.;
replace lrestbisw=log(1+abs(otherwealth)) if otherwealth>=0;
replace lrestbisw=-log(1+abs(otherwealth)) if otherwealth<0;
*********** Dummies for housing wealth ************;

gen housingw1=0;
replace housingw1=1 if housewealth<=10000;
gen housingw2=0;
replace housingw2=1 if housewealth>10000 & housewealth<=80000;
gen housingw3=0;
replace housingw3=1 if housewealth>80000 & housewealth<=200000;
gen housingw4=0;
replace housingw4=1 if housewealth>200000 & housewealth<=500000;
gen housingw5=0;
replace housingw5=1 if housewealth>500000;

*********** Dummies for business wealth ************;

gen busloanw1=0;
replace busloanw1=1 if buswealth<=10000;
gen busloanw2=0;
replace busloanw2=1 if buswealth>10000 & buswealth<=80000;
gen busloanw3=0;
replace busloanw3=1 if buswealth>80000 & buswealth<=200000;
gen busloanw4=0;
replace busloanw4=1 if buswealth>200000 & buswealth<=500000;
gen busloanw5=0;
replace busloanw5=1 if buswealth>500000;




*********** Dummies for other debts wealth ************;

gen restbisw1=0;
replace restbisw1=1 if otherwealth<=10000;
gen restbisw2=0;
replace restbisw2=1 if otherwealth>10000 & otherwealth<=80000;
gen restbisw3=0;
replace restbisw3=1 if otherwealth>80000 & otherwealth<=200000;
gen restbisw4=0;
replace restbisw4=1 if otherwealth>200000 & otherwealth<=500000;
gen restbisw5=0;
replace restbisw5=1 if otherwealth>500000;

foreach f of var * { ;
	rename `f' `f'_imp`x' ;
} ;
rename h_number_imp`x' h2002;
drop p6*;
save wave2002_imp`x'.dta, replace;

};


cd "H:\Mi unidad\Grant_new\EFF";
use "H:\Mi unidad\Grant_new\EFF\Imputation1\wave2002_imp1.dta";
joinby h2002 using "H:\Mi unidad\Grant_new\EFF\Imputation2\wave2002_imp2";
joinby h2002 using "H:\Mi unidad\Grant_new\EFF\Imputation3\wave2002_imp3";
joinby h2002 using "H:\Mi unidad\Grant_new\EFF\Imputation4\wave2002_imp4";
joinby h2002 using "H:\Mi unidad\Grant_new\EFF\Imputation5\wave2002_imp5";



save "H:\Mi unidad\Grant_new\wave2002.dta", replace;


*************************** 2005 *************************************;
**********************************************************************;


foreach x in 1 2 3 4 5{; 


cd "H:\Mi unidad\Grant_new\EFF\Imputation`x'";


use seccion6_2005_imp`x'.dta, clear;

joinby h_2005 using otras_secciones_2005_imp`x'.dta;

gen year=2005;

********************************************************************;
** Annual and monthly consumer price index to be used (base 2010) **;
********************************************************************;

gen acpi=81.06;
replace acpi=88.96 if year==2005;
replace acpi=98.52 if year==2008;
replace acpi=103.20 if year==2011;
replace acpi=107.05 if year==2014;

gen mcpi=82.73 					 /* mean oct02-may03 */;
replace mcpi=91.14 if year==2005 /* mean nov05-may06 */;
replace mcpi=98.10 if year==2008 /* mean nov08-jun09 */;
replace mcpi=104.33 if year==2011 /* mean oct11-apr12 */;
replace mcpi=106.42 if year==2014 /* mean sept14-mar15*/;

********************************************************************;
********************************************************************;



*NET WEALTH AND INCOME;

*1.- FOR THE PERCENTAGE OF HOUSEHOLDS OWNING THAT ASSET;

*REAL ASSETS;

*MAIN RESIDENCE;
*To calculate the percentage of households that own their main residence we use the variable p2_1;
gen owner=0;
replace owner=1 if p2_1==2;

gen renter=0 /*renter or (only 2014) renter with purchase option*/;
replace renter=1 if p2_1==1;

gen freeuse=0;
replace freeuse=1 if p2_1==3;

*OTHER REAL ESTATE PROPERTIES;
*To calculate the percentage of households that own other real estate properties we use the variable np2_32;

gen np2_32=((p2_32==1 & p2_33>=1 & p2_33~=. & p2_39_1>0 & p2_39_1~=.)|
            (p2_32==1 & p2_33>=2 & p2_33~=. & p2_39_2>0 & p2_39_2~=.)|
            (p2_32==1 & p2_33>=3 & p2_33~=. & p2_39_3>0 & p2_39_3~=.)|
            (p2_32==1 & p2_33>3  & p2_33~=. & p2_39_4>0 & p2_39_4~=.));

gen othowner=.;
replace othowner=1 if np2_32==1;
replace othowner=0 if np2_32==0;

*JEWELLERY, WORKS OF ART, ANTIQUES;
*To calculate the percentage of households that own jewellery, works of art and antiques we use the variable p2_82;
gen np2_82=(p2_82==1 & p2_84>0 & p2_84~=.);

gen jewel=.;
replace jewel=0 if np2_82==0;
replace jewel=1 if np2_82==1;


*VALOR DEL NEGOCIO POR TRABAJOS POR CUENTA PROPIA;
*VALUE OF BUSINESSES RELATED TO SELF-EMPLOYMENT;
gen haveneg=(p6_1c2_1==1|p6_1c2_2==1|p6_1c2_3==1|p6_1c2_4==1|p6_1c2_5==1|p6_1c2_6==1| p6_1c2_7==1| p6_1c2_8==1| p6_1c2_9==1);


*PRIMERO;
*CALCULAR PARA CADA TRABAJO POR CTA PROPIA DE CADA MIEMBRO LOS VALORES DE 
 *(i)INMUEBLES Y EDIFICIOS,DESCONTANDO EL VALOR DE LOS ACTIVOS YA DECLARADOS COMO PROPIEDADES INMOBILIARIAS

 *(ii)NEGOCIO INCLUIDO MAQUINARIA Y VEHICULOS. (AQUI NO SE DESCUENTAN VEHICULOS YA INCLUIDOS PORQUE NO SE CONSIDERAN VEHICULOS EN RIQUEZA SINO QUE FORMAN PARTE DE NEGOCIO);

*LUEGO SE SUMAN ESTOS DOS CONCEPTOS DE VALOR NETO;
*LUEGO A ESA SUMA SE LE APLICA EL PORCENTAJE QUE PERTENECE AL MIEMBRO (PARA PROFESIONALES, PROP.UNICOS, AUTONOMOS -opcion 1 en las p6_37- SE SUPONE QUE ES 1);

*FIRST;
*DETERMINE FOR EACH SELF-EMPLOYMENT JOB OF EACH MEMBER THE VALUES OF
 *(i)REAL ESTATE PROPERTIES AND BUILDINGS, SUBSTRACTING THE VALUE OF THE ASSETS ALREADY DECLARED AS REAL ESTATE PROPERTIES
 *(ii)BUSINESS INCLUDING MACHINERY AND VEHICLES. (HERE WE DO NOT SUBSTRACT VEHICLES ALREADY INCLUDED BECAUSE VEHICLES ARE NOT CONSIDERED WEALTH IF THEY ARE NOT PART OF A BUSINESS);  
 
*THEN BOTH NET VALUES ARE ADDED;
*THEN TO THAT RESULT WE APPLY THE PERCENTAGE THAT BELONGS TO THE MEMBER (FOR INDEPENDENT PROFESSIONALS, SOLE PROPRIETORS, SELF-EMPLOYED.-option 1 in p6_37- is assumed);


forvalues m=1/6   {;

	forvalues j=1/3 {;

	display _newline(1) `m' `j';

	gen valter_`m'_`j'=0;
	gen valneg_`m'_`j'=0;
	
	gen indter_`m'_`j'=(p6_391_`m'_`j'==1);
	gen indc1_`m'_`j'=(p6_392c1_`m'_`j'==1);
	gen indc2_`m'_`j'=(p6_392c2_`m'_`j'==1);
	gen indc3_`m'_`j'=(p6_392c3_`m'_`j'==1);
	gen indc4_`m'_`j'=(p6_392c4_`m'_`j'==1);
	gen indc5_`m'_`j'=(p6_392c5_`m'_`j'==1);

	replace valter_`m'_`j'=p6_39_`m'_`j' if (p6_39_`m'_`j'>0 & p6_39_`m'_`j'~=.);
	replace valter_`m'_`j'=valter_`m'_`j'- p2_5*(indter_`m'_`j')*(indc1_`m'_`j') 
	if (p2_5>0 & p2_5~=.);

	replace valter_`m'_`j'=valter_`m'_`j'- p2_39_1*(indter_`m'_`j')*(indc2_`m'_`j') 
	if (p2_39_1>0 & p2_39_1~=.);
	replace valter_`m'_`j'=valter_`m'_`j'- p2_39_2*(indter_`m'_`j')*(indc3_`m'_`j') 
	if (p2_39_2>0 & p2_39_2~=.);
	replace valter_`m'_`j'=valter_`m'_`j'- p2_39_3*(indter_`m'_`j')*(indc4_`m'_`j') 
	if (p2_39_3>0 & p2_39_3~=.);
	replace valter_`m'_`j'=valter_`m'_`j'- p2_39_4*(indter_`m'_`j')*(indc5_`m'_`j') 
	if (p2_39_4>0 & p2_39_4~=.);

	display _newline(1);

	replace valter_`m'_`j'=0 if valter_`m'_`j'<0;


	display _newline(1);
	
	replace valneg_`m'_`j'=p6_40_`m'_`j' if (p6_40_`m'_`j'>0 & p6_40_`m'_`j'~=.);
      
	display _newline(1);
	gen coef_`m'_`j'=1;
	replace coef_`m'_`j'=(p6_3824_`m'_`j')/100 
	if (p6_3824_`m'_`j'>0 & p6_3824_`m'_`j'~=. & p6_37_`m'_`j'==2);

	replace coef_`m'_`j'=(p6_3832_`m'_`j')/100 
	if (p6_3832_`m'_`j'>0 & p6_3832_`m'_`j'~=. & p6_37_`m'_`j'==3);
	gen valind_`m'_`j'=(valter_`m'_`j'+valneg_`m'_`j')*coef_`m'_`j';
	
	};

};


*SEGUNDO;
*PARA NO REPETIR VALORES DE UN MISMO NEGOCIO EN QUE TRABAJAN VARIOS MIEMBROS DEL HOGAR:
 *(i) PARA MIEMBROS EMPRESA FAMILIAR O NO FAMILIAR.
     (-opciones 2 o 3 en la p6_37)  COMO SE LES APLICA EL COEFICIENTE INDIVIDUAL,  SE SUMA Y NO SE DUPLICA 
* (ii)PARA PROFESIONALES, AUTONOMOS (opcion 1 en p6_37) SE HACE LO SIGUIENTE
	*(a) SE SUMA SIEMPRE QUE DIGA QUE SOLO EL TRABAJA EN ESE NEGOCIO (P6_35==1)
	*(b) PARA P6_35>1
		*SE SUMA SIEMPRE SI ES LA PERSONA DE REFERENCIA;
		*SI ES 2º MIEMBRO SOLO SE SUMA 
        *    SI NO HAY NINGUN TRABAJO COMO CTA PROPIA
		* DE LA PERSONA DE REFERENCIA EN QUE P6_35>1;
		*SI ES 3er MIEMBRO SOLO SE SUMA 
            * SI NO HAY NINGUN TRABAJO COMO CTA PROPIA
		* DE LA PERSONA DE REFERENCIA EN QUE P6_35>1 
           *  NI NINGUN TRABAJO COMO CTA PROPIA
		* DEL 2º MIEMBRO EN QUE P6_35>1;
		*Y ASI SUCESIVAMENTE PARA EL RESTO DE MIEMBROS;

*SECOND;
*TO AVOID DOUBLE COUNTING OF THE SAME BUSINESS IN WHICH SEVERAL HOUSEHOLD MEMBERS ARE WORKING:
 *(i) FOR MEMBERS OR PARTNERS OF A FAMILY OR NON-FAMILY FIRM.
 *    (-options 2 or 3 in p6_37)  SINCE INDIVIDUAL COEFFICIENTS ARE APPLIED, NO DOUBLE COUNTING
 *(ii)FOR PROFESSIONALS, SELF-EMPLOYED (OPTION 1 IN P6_37):
(a)	ADDED WHENEVER THE HOUSEHOLD MEMBER IS THE ONLY ONE WORKING IN THAT BUSINESS (P6_35==1)
(b)	FOR P6_35>1
*IT IS ALWAYS ADDED IF THE HOUSEHOLD MEMBER IS THE REFERENCE PERSON;
*IF THE HOUSEHOLD MEMBER IS THE SECOND MEMBER IT IS ONLY ADDED IF THERE IS NO SELF-EMPLOYMENT JOB OF THE REFERENCE PERSON IN WHICH P6_35>1;
*IF THE HOUSEHOLD MEMBER IS THE THIRD MEMBER IT IS ONLY ADDED IF THERE IS NO SELF-EMPLOYMENT JOB OF THE REFERENCE PERSON IN WHICH P6_35>1 NOR ANY SELF-EMPLOYMENT JOB OF THE SECOND MEMBER IN WHICH P6_35>1;
*THE SAME PROCEDURE APPLIES FOR THE REST OF THE HOUSEHOLD MEMBERS; 


gen valhog=0;

gen noinsum2=(p6_35_1_1>1 & p6_35_1_1~=. & p6_37_1_1==1|
		  p6_35_1_2>1 & p6_35_1_2~=. & p6_37_1_2==1|
		  p6_35_1_3>1 & p6_35_1_3~=. & p6_37_1_3==1);
gen noinsum3=(noinsum2==1|
		  p6_35_2_1>1 & p6_35_2_1~=. & p6_37_2_1==1|
		  p6_35_2_2>1 & p6_35_2_2~=. & p6_37_2_2==1|
		  p6_35_2_3>1 & p6_35_2_3~=. & p6_37_2_3==1);
gen noinsum4=(noinsum3==1|
		  p6_35_3_1>1 & p6_35_3_1~=. & p6_37_3_1==1|
		  p6_35_3_2>1 & p6_35_3_2~=. & p6_37_3_2==1|
		  p6_35_3_3>1 & p6_35_3_3~=. & p6_37_3_3==1);
gen noinsum5=(noinsum4==1|
		  p6_35_4_1>1 & p6_35_4_1~=. & p6_37_4_1==1|
		  p6_35_4_2>1 & p6_35_4_2~=. & p6_37_4_2==1|
		  p6_35_4_3>1 & p6_35_4_3~=. & p6_37_4_3==1);
gen noinsum6=(noinsum5==1|
		  p6_35_5_1>1 & p6_35_5_1~=. & p6_37_5_1==1|
		  p6_35_5_2>1 & p6_35_5_2~=. & p6_37_5_2==1|
		  p6_35_5_3>1 & p6_35_5_3~=. & p6_37_5_3==1);
	

forvalues m=1/6   {;
	forvalues j=1/3 {;

	replace valhog=valhog+valind_`m'_`j' if ((valind_`m'_`j'>0 & valind_`m'_`j'~=.) & (
		p6_37_`m'_`j'==2|p6_37_`m'_`j'==3|
		p6_37_`m'_`j'==1 & p6_35_`m'_`j'==1|

		p6_37_`m'_`j'==1 & p6_35_`m'_`j'>1 & p6_35_`m'_`j'~=. & `m'==1|
            p6_37_`m'_`j'==1 & p6_35_`m'_`j'>1 & p6_35_`m'_`j'~=. & `m'==2 & noinsum2==0|
            p6_37_`m'_`j'==1 & p6_35_`m'_`j'>1 & p6_35_`m'_`j'~=. & `m'==3 & noinsum3==0|
            p6_37_`m'_`j'==1 & p6_35_`m'_`j'>1 & p6_35_`m'_`j'~=. & `m'==4 & noinsum4==0|

            p6_37_`m'_`j'==1 & p6_35_`m'_`j'>1 & p6_35_`m'_`j'~=. & `m'==5 & noinsum5==0|
            p6_37_`m'_`j'==1 & p6_35_`m'_`j'>1 & p6_35_`m'_`j'~=. & `m'==6 & noinsum6==0 ));

	};
};

*Para calcular las proporciones de hogares con algo de cuenta propia generamos una nueva variable que tiene en cuenta que se declare un valor positivo para el negocio;
*To calculate the percentages of households with some business we generate a new variable that takes into account that a positive value is held for the business; 

gen havenegval =(haveneg==1 & valhog>0);

 

*ALGUN TIPO DE ACTIVO REAL;
*SOME KIND OF REAL ASSET;

gen  tienereal=(p2_1==2|p2_32==1|p2_82==1| havenegval==1);


*ACTIVOS FINANCIEROS;
*FINANCIAL ASSETS;


*ACCOUNTS AND DEPOSITS USABLE FOR PAYMENTS;
*To calculate the percentage of households that own accounts and deposits usable for payments and that declare a strictly positive value 
*for the balance of those accounts we generate a new variable;

gen np4_5=(p4_5==1 & p4_7_3>0 & p4_7_3~=.);
rename np4_5 account_pay;
label var account_pay "households that own accounts and deposits usable for payments and that declare a strictly positive value";

*LISTED SHARES;
*To calculate the percentage of households that own listed shares we use the variable p4_10;
rename p4_10 listshare;
label var listshare "household that own listed shares";


*UNLISTED SHARES AND OTHER EQUITY;
*To calculate the percentage of households that own unlisted shares and other equity and that declare a strictly positive
* value for that portfolio we generate a new variable;

gen np4_18=(p4_18==1 & p4_24>0 & p4_24~=.);
rename np4_18 unlistshare;
label var unlistshare "household that own unlisted shares and other equity";


*FIXED-INCOME SECURITIES;
*To calculate the percentage of households that own fixed-income securities we use the variable p4_33;
rename p4_33 fixsec;
label var fixsec "household that own fixed-income securities ";

*MUTUAL FUNDS (FFII);
*To calculate the percentage of households that own mutual funds we use the variable p4_27;
rename p4_27 mutfunds;
label var mutfunds "household that own mutual funds";

*CUENTAS VIVIENDA Y CUENTAS NO UTILIZABLES PARA REALIZAR PAGOS;
*Para calcular la proporción de hogares que poseen cuentas y depósitos no utilizables para realizar pagos generamos una nueva variable cuentas;

*HOUSE-PURCHASE SAVINGS ACCOUNTS AND ACCOUNTS NOT USABLE FOR PAYMENTS;
*To calculate the percentage of households that own accounts and deposits not usable for payments we generate a new variable cuentas;

gen cuentas=(p4_3==1|p4_4==1);
rename cuentas account_nopay;
label var account_nopay "household that own accounts and deposits not usable for payments";


*PENSION SCHEMES (plan pensiones);
*To calculate the percentage of households that own pension schemes we use the variable p5_1;
rename p5_1 penplan;
label var penplan "household that own pension schemes";

*SEGUROS DE VIDA;
*Para calcular la proporción de hogares que tienen seguros tipo unit linked o mixto generamos una nueva variable;

*To calculate the percentage of households that own unit-linked or mixed life insurance we generate a new variable;

gen seguro=(p5_13_1==2| p5_13_2==2| p5_13_3==2| p5_13_4==2| p5_13_5==2| p5_13_6==2| p5_13_1==3| p5_13_2==3| p5_13_3==3| p5_13_4==3| p5_13_5==3| p5_13_6==3);
rename seguro lifeinsur;
label var lifeinsur "household that own unit-linked or mixed life insurance";

*PLANES DE PENSIONES INCLUYENDO SEGUROS DE VIDA DE INVERSION O MIXTOS;
*PENSION SCHEMES INCLUDING UNIT-LINKED OR MIXED LIFE INSURANCE;

gen penseg=(penplan==1|lifeinsur==1);

*OTHER FINANCIAL ASSETS; 

*To calculate the percentage of households to whom the business or other people owe money we generate the variable sideuda; 


*PROGRAMA PARA CALCULAR LO QUE LES DEBEN LOS NEGOCIOS A LOS DISTINTOS MIEMBROS DEL HOGAR (P6_44);
*PROGRAM TO OBTAIN WHAT THE BUSINESSES OWE TO THE DIFFERENT HOUSEHOLD MEMBERS (P6_44);

gen valdeuhog=0;
gen havedeuhog=0;

forvalues m=1/6   {;

	forvalues j=1/3 {;

	display _newline(1) `m' `j';
	

	replace valdeuhog=valdeuhog+p6_44_`m'_`j' 
	if (p6_44_`m'_`j'>0 & p6_44_`m'_`j'~=.);

	replace havedeuhog=1 if (p6_43_`m'_`j'==1);


	};

};
	
gen sideuda=((havedeuhog ==1 & valdeuhog>0)|(p4_37==1 & p4_38>0 & p4_38~=.));
rename sideuda creditor;
label var creditor "household to whom the business or other people owe money";

*ALGUN TIPO DE ACTIVO FINANCIERO;
*SOME TYPE OF FINANCIAL ASSET;

gen tienefin=(account_pay==1|listshare==1|unlistshare==1|fixsec==1|mutfunds==1|account_nopay==1|penplan==1|lifeinsur==1|creditor==1);

*ALGUN TIPO DE ACTIVO;
*SOME TYPE OF ASSET;

gen tiene=(tienereal==1|tienefin==1);
rename tiene anyasset;




*2.- PARA EL VALOR DE DICHOS ACTIVOS;
*2.- FOR THE VALUE OF THOSE ASSETS;

*ACTIVOS REALES;
*REAL ASSETS;

*MAIN RESIDENCE;
*To obtain the value of the main residence we use the variable p2_5;
rename p2_5 vmresid;
label var vmresid "value of the main residence";

*OTHER REAL ESTATE PROPERTIES;
*To obtain the value of the other real estate properties we generate a new variable;

gen otraspr=0;
replace otraspr=otraspr+p2_39_1*(p2_37_1/100) if (p2_33>=1 & p2_33~=. & p2_39_1>=0 & p2_39_1~=. & p2_37_1>0 & p2_37_1~=.);
replace otraspr=otraspr+p2_39_2 *(p2_37_2/100) if (p2_33>=2 & p2_33~=. & p2_39_2>=0 & p2_39_2~=. & p2_37_2>0 & p2_37_2~=.);
replace otraspr=otraspr+p2_39_3* (p2_37_3/100) if (p2_33>=3 & p2_33~=. & p2_39_3>=0 & p2_39_3~=. & p2_37_3>0 & p2_37_3~=.);
replace otraspr=otraspr+p2_39_4 if (p2_33>3 & p2_33~=. & p2_39_4>=0 & p2_39_4~=.);

rename otraspr vothprop;
label var vothprop "value of the other real estate properties";


*JEWELLERY, WORKS OF ART, ANTIQUES;
*To obtain the value of the jewellery, works of art and antiques we use the variable p2_84;
rename p2_84 vjewel;
label var vjewel "value of the jewellery, works of art and antiques";

*VALOR DEL NEGOCIO POR TRABAJOS POR CUENTA PROPIA;
*la mediana del valor del negocio será la mediana de valhog if havenegval==1; 

*TBD;

*VALUE OF THE BUSINESS RELATED TO SELF-EMPLOYMENT;
*The median of the business value is equal to the median of valhog if havenegval==1;


*ACTIVOS FINANCIEROS;
*FINANCIAL ASSETS;

*CUENTAS Y DEPOSITOS UTILIZABLES PARA REALIZAR PAGOS;
*Para calcular el saldo de las cuentas y depósitos para realizar pagos utilizamos la variable p4_7_3;


*ACCOUNTS AND DEPOSITS USABLE FOR PAYMENTS;
*To obtain the balance of the accounts and deposits usable for payments we use the variable p4_7_3;
rename p4_7_3 vaccount_pay;



*ACCIONES COTIZADAS EN BOLSA;
*Para calcular el valor de las acciones cotizadas utilizamos la variable p4_15;


*LISTED SHARES;
*To obtain the value of the listed shares we use the variable p4_15;
rename p4_15 vlistshare;

*ACCIONES NO COTIZADAS EN BOLSA Y PARTICIPACIONES;
*Para calcular el valor de las acciones no cotizadas y participaciones utilizamos la variable p4_24;

*UNLISTED SHARES ANDOTHER EQUITY;
*To obtain the value of the unlisted shares and other equity we use the variable p4_24;
rename p4_24 vunlist;

*VALORES DE RENTA FIJA;
*Para calcular el valor de los valores de renta fija utilizamos la variable p4_35;

*FIXED-INCOME SECURITIES;
*To obtain the value of the fixed-income securities we use the variable p4_35;

rename p4_35 vfixsec;

*FONDOS DE INVERSION;
*Para calcular el valor total de los fondos de inversión utilizamos la variable allf calculada como (i) la suma de los valores de cada uno de los fondos 
*de inversión que posee el hogar (p4_31_i, i=1,…,10) si el número de estos fondos es menor o igual a 10, y (ii) el valor total de los fondos de inversión 
*del hogar si posee más de 10 fondos (p4_28a);

*MUTUAL FUNDS;
*To obtain the total value of mutual funds we use the variable allf calculated as (i) the addition of the values of each mutual fund that the household
* owns (p4_31_i, i=1,…,10) if the number of these funds is 10 or less, and (ii) the household mutual funds’ total value if this one owns more than 10 (p4_28a);

egen allf=rowtotal(p4_31*);
replace allf=p4_28a if p4_28>10;
label var allf "Total value of mutual funds";


*CUENTAS VIVIENDA Y CUENTAS NO UTILIZABLES PARA REALIZAR PAGOS;
*Para calcular el saldo de las cuentas y depósitos no utilizables para realizar pagos generamos una nueva variable;

*HOME-PURCHASE SAVINGS ACCOUNTS AND ACCOUNTS NOT USABLE FOR PAYMENTS;
*To obtain the balance of the accounts and deposits not usable for payments we generate a new variable;  

gen salcuentas=0;
replace salcuentas = salcuentas +p4_7_1 if (p4_3==1 & p4_7_1>=0 & p4_7_1~=. );
replace salcuentas = salcuentas + p4_7_2 if (p4_4==1 & p4_7_2>=0 & p4_7_2~=.);
rename salcuentas vaccount_nopay;
label var vaccount_nopay "balance of the accounts and deposits not usable for payments";

*PLANES DE PENSIONES;
*Para calcular valor actualizado de los planes de pensiones generamos una nueva variable;

*PENSION SCHEMES;
*To obtain the current value of the pension schemes we generate a new variable;

gen valor=0; 

replace valor = valor +p5_7_1 if (penplan==1 & p5_7_1>=0 & p5_7_1~=. ); 
replace valor = valor + p5_7_2 if (penplan==1 & p5_7_2>=0 & p5_7_2~=.);
replace valor = valor + p5_7_3 if (penplan==1 & p5_7_3>=0 & p5_7_3~=.);
replace valor = valor + p5_7_4 if (penplan==1 & p5_7_4>=0 & p5_7_4~=.);
replace valor = valor + p5_7_5 if (penplan==1 & p5_7_5>=0 & p5_7_5~=.);
replace valor = valor + p5_7_6 if (penplan==1 & p5_7_6>=0 & p5_7_6~=.);
replace valor = valor + p5_7_7 if (penplan==1 & p5_7_7>=0 & p5_7_7~=.);
replace valor = valor + p5_7_8 if (penplan==1 & p5_7_8>=0 & p5_7_8~=.);

rename valor vpenplan;
label var vpenplan "current value of the pension schemes";

*No consideramos las mutualidades;
*We do not consider mutual insurance;

*SEGUROS DE VIDA;
*Para calcular el valor de estos seguros tipo unit linked o mixto generamos una nueva variable;

*LIFE INSURANCE;
*To obtain the value of the unit-linked or mixed life insurance we generate a new variable;


gen valseg=0;

replace valseg = valseg +p5_14_1 if ((p5_13_1==2| p5_13_1==3) & p5_14_1>0 & p5_14_1~=.);
replace valseg = valseg +p5_14_2 if ((p5_13_2==2| p5_13_2==3) & p5_14_2>0 & p5_14_2~=.);
replace valseg = valseg +p5_14_3 if ((p5_13_3==2| p5_13_3==3) & p5_14_3>0 & p5_14_3~=.);
replace valseg = valseg +p5_14_4 if ((p5_13_4==2| p5_13_4==3) & p5_14_4>0 & p5_14_4~=.);
replace valseg = valseg +p5_14_5 if ((p5_13_5==2| p5_13_5==3) & p5_14_5>0 & p5_14_5~=.);
replace valseg = valseg +p5_14_6 if ((p5_13_6==2| p5_13_6==3) & p5_14_6>0 & p5_14_6~=.);

rename valseg vlifeinsur;
label var vlifeinsur "value of the unit-linked or mixed life insurance";

*PLANES DE PENSIONES INCLUYENDO SEGUROS DE VIDA DE INVERSION O MIXTOS;
*PENSION SCHEMES INCLUDING UNIT-LINKED OR MIXED LIFE INSURANCE;

gen valpenseg=vpenplan+vlifeinsur;
rename valpenseg vpeninsur;
label var vpeninsur "value of pension schemes plus unit-linked or mixed life insurance";

*OTROS ACTIVOS FINANCIEROS;
*Para calcular el valor de la mediana de lo que se debe al hogar, utilizamos las variables valdeuhog y p4_38 y generamos una nueva variable;

*OTHER FINANCIAL ASSETS;
*To obtain the median of how much is owed to the household, we use the variables valdeuhog and p4_38 and generate a new variable; 

gen odeuhog=0;

replace odeuhog = odeuhog +valdeuhog if (valdeuhog>0);
replace odeuhog = odeuhog +p4_38 if (p4_38>0 & p4_38~=.);

rename odeuhog vcreditor;
label var vcreditor "how much is owed to the household";

*CUADRO 7: PROPORCION DE HOGARES Y MEDIANA DEL VALOR DE LOS DISTINTOS TIPOS DE DEUDA PENDIENTES;
*TABLE 7: PERCENTAGE OF HOUSEHOLDS AND VALUE’S MEDIAN OF THE DIFFERENT TYPES OF OUTSTANDING DEBT;

*DEUDAS  CLASIFICADAS POR TIPO DE ACTIVO INMOBILIARIO (TODO TIPO DE PRESTAMOS);
*DEBT CLASSIFIED BY TYPE OF REAL ESTATE ASSET (ALL KIND OF LOANS);

*VIVIENDA PRINCIPAL;
*MAIN RESIDENCE;

*Para calcular la proporción de hogares que tienen deudas pendientes de préstamos solicitados para la adquisición de la vivienda principal, utilizamos p2_8;
*To obtain the percentage of households that have outstanding debt from loans used to purchase their main residence, we use p2_8;
rename p2_8 debtmresid;
label var debtmresid "have outstanding debt from loans used to purchase main residence";

*Para calcular el valor de las deudas pendientes de préstamos solicitados para la adquisición de la vivienda principal, generamos una nueva variable;
*To obtain the value of the outstanding debts from loans used to purchase their main residence, we generate a new variable;

gen dvivpral=0;

replace dvivpral= dvivpral +p2_12_1 if  (p2_8a>=1 & p2_8a~=. & p2_12_1>0 & p2_12_1~=.);

replace dvivpral= dvivpral + p2_12_2 if (p2_8a>=2 & p2_8a~=. &  p2_12_2>0 & p2_12_2~=.);

replace dvivpral= dvivpral +p2_12_3  if (p2_8a>=3 & p2_8a~=. & p2_12_3>0 & p2_12_3~=.);

replace dvivpral= dvivpral +p2_12_4  if (p2_8a>3 & p2_8a~=. & p2_12_4>0 & p2_12_4~=.);

rename dvivpral vdebtmresid;
label var vdebtmresid "value of outstanding debts from loans used to purchase main residence";

*OTRAS PROPIEDADES INMOBILIARIAS DIFERENTES DE LA VIVIENDA PRINCIPAL;
*OTHER REAL ESTATE PROPERTIES DIFFERENT FROM THE MAIN RESIDENCE;

*Para calcular la proporción de hogares que tienen deudas pendientes de préstamos solicitados para la adquisición de otras propiedades inmobiliarias diferentes de la vivienda principal, generamos una nueva variable;

*To obtain the percentage of households that have outstanding debts from loans used to purchase other real estate properties different from the main 
*residence, we generate a new variable;

gen dpdte=(p2_50_1==1|p2_50_2==1|p2_50_3==1|p2_50_4==1);
rename dpdte debtothprop;
label var debtothprop "have outstanding debts from loans used to purchase other real estate properties";

*Para calcular el valor de las deudas pendientes de préstamos solicitados para la adquisición de otras propiedades inmobiliarias diferentes de la vivienda principal, generamos cuatro nuevas variables;

*To obtain the value of the outstanding debts from loans used to purchase other real estate properties different from the main residence, we generate
* four new variables;

*PARA LA PRIMERA PROPIEDAD INMOBILIARIA;
*FOR THE FIRST REAL ESTATE PROPERTY;

gen dprop1=0;

replace dprop1= dprop1+p2_55_1_1 if (p2_51_1>=1 & p2_51_1~=.  &  p2_55_1_1>0 & p2_55_1_1~=.);

replace dprop1= dprop1+ p2_55_1_2 if (p2_51_1>=2 & p2_51_1~=.  & p2_55_1_2>0 & p2_55_1_2~=.);

replace dprop1= dprop1+p2_55_1_3  if (p2_51_1>=3 & p2_51_1~=.  & p2_55_1_3>0 & p2_55_1_3~=.);


*PARA LA SEGUNDA PROPIEDAD INMOBILIARIA;
*FOR THE SECOND REAL ESTATE PROPERTY;

gen dprop2=0;

replace dprop2= dprop2+p2_55_2_1 if (p2_51_2>=1 & p2_51_2~=. & p2_55_2_1>0 & p2_55_2_1~=.);

replace dprop2= dprop2+ p2_55_2_2 if (p2_51_2>=2 & p2_51_2~=. & p2_55_2_2>0 & p2_55_2_2~=.);

replace dprop2= dprop2+ p2_55_2_3  if (p2_51_2>=3 & p2_51_2~=. & p2_55_2_3>0 & p2_55_2_3~=.);


*PARA LA TERCERA PROPIEDAD INMOBILIARIA;
*FOR THE THIRD REAL ESTATE PROPERTY;

gen dprop3=0;

replace dprop3= dprop3+p2_55_3_1 if (p2_51_3>=1 & p2_51_3~=. & p2_55_3_1>0 & p2_55_3_1~=.);

replace dprop3= dprop3+ p2_55_3_2 if (p2_51_3>=2 & p2_51_3~=. & p2_55_3_2>0 & p2_55_3_2~=.);

replace dprop3= dprop3+ p2_55_3_3  if (p2_51_3>=3 & p2_51_3~=. & p2_55_3_3>0 & p2_55_3_3~=.);


*PARA EL RESTO DE PROPIEDADES INMOBILIARIAS CUANDO HAY MAS DE TRES;
*FOR THE REST OF REAL ESTATE PROPERTIES WHEN THESE ARE MORE THAN THREE;

gen dprop4=0;

replace dprop4= dprop4+p2_55_4 if (p2_55_4>0 & p2_55_4~=.);

forvalues i=1(1)4{;
rename dprop`i' vdebtprop`i';
};

label var vdebtprop1 "value of the outstanding debts from loans used to purchase other real estate property #1";
label var vdebtprop2 "value of the outstanding debts from loans used to purchase other real estate property #2";
label var vdebtprop3 "value of the outstanding debts from loans used to purchase other real estate property #3";
label var vdebtprop4 "value of the outstanding debts from loans used to purchase other real estate properties #4";


*CONSIDERANDO CONJUNTAMENTE TODAS LAS PROPIEDADES INMOBILIARIAS DIFERENTES DE LA VIVIENDA PRINCIPAL;
*CONSIDERING ALL REAL ESTATE PROPERTIES DIFFERENT FROM THE MAIN RESIDENCE;

gen deuoprop= vdebtprop1+ vdebtprop2+ vdebtprop3+ vdebtprop4 ; 
rename deuoprop vdebtothprop;
label var vdebtothprop "value of the outstanding debts from loans used to purchase other real estate properties";

*DEUDAS PENDIENTES DE PRESTAMOS SOLICITADOS PARA LA ADQUISICION DE LA VIVIENDA PRINCIPAL CON GARANTIA HIPOTECARIA;
*OUTSTANDING DEBTS FROM LOANS WITH MORTGAGE GUARANTEE USED FOR THE PURCHASE OF THE MAIN RESIDENCE;

*Para calcular la proporción de hogares que tienen deudas pendientes de préstamos CON garantía hipotecaria solicitados para la adquisición de la vivienda principal, generamos una nueva variable;
*To obtain the percentage of households that have outstanding debts from loans with mortgage guarantee used for the purchase of the main residence, 
* we generate a new variable;

gen dpdtehipo = (p2_9_1==1|p2_9_2==1|p2_9_3==1|p2_9_4==1);
rename dpdtehipo mortgmresid;
label var mortgmresid " have mortgage for the purchase of the main residence";

*Para calcular el valor de las deudas pendientes de préstamos CON garantía hipotecaria solicitados para la adquisición de la vivienda principal, generamos una nueva variable;
*To obtain the value of the outstanding debts from loans with mortgage guarantee used for the purchase of the main residence, we generate a new variable;

gen deuhipv =0;

replace deuhipv= deuhipv + p2_12_1 if (p2_8a>=1 & p2_8a~=. & p2_9_1==1 & p2_12_1>0 & p2_12_1~=.);

replace deuhipv = deuhipv + p2_12_2 if (p2_8a>=2 & p2_8a~=. & p2_9_2==1 &  p2_12_2>0 & p2_12_2~=.);

replace deuhipv= deuhipv +p2_12_3  if (p2_8a>=3 & p2_8a~=. & p2_9_3==1 &  p2_12_3>0 & p2_12_3~=.);

replace deuhipv= deuhipv +p2_12_4  if (p2_8a>3 & p2_8a~=. & p2_8a~=. & p2_9_4==1 &  p2_12_4>0 & p2_12_4~=.);

rename deuhipv vmortgmresid;
label var vmortgmresid "value of outstanding mortgages for the purchase of the main residence";


*OTRAS DEUDAS PENDIENTES NO ASOCIADAS A LA ADQUISICION DE ACTIVOS INMOBILIARIOS;
*OTHER OUTSTANDING DEBT NOT RELATED TO THE PURCHASE OF REAL ESTATE ASSETS;

*DEUDAS PENDIENTES DE PRESTAMOS HIPOTECARIOS Y OTROS PRESTAMOS CON GARANTIA REAL;
*OUTSTANDING DEBTS FROM MORTGAGES AND OTHER SECURED LOANS);

*Para calcular la proporción de hogares que tienen deudas pendientes por prestamos hipotecarios y otros préstamos con garantía real generamos una nueva variable;
*To obtain the percentage of households that have outstanding debts from mortgages and other secured loans we generate a new variable;

gen hipo=(p3_2_1==1| p3_2_2==1| p3_2_3==1| p3_2_4==1|p3_2_5==1| p3_2_6==1| p3_2_7==1| p3_2_8==1|
p3_2_1==2| p3_2_2==2| p3_2_3==2| p3_2_4==2|p3_2_5==2| p3_2_6==2| p3_2_7==2| p3_2_8==2);

rename hipo mortgoth;
label var mortgoth "have mortgage for other porpuses";

*Para calcular el valor de las deudas pendientes por prestamos hipotecarios y otros préstamos con garantía real generamos una nueva variable;
*To obtain the value of the outstanding debts from mortgages and other loans with real guarantee we generate a new variable;

gen phipo=0;

replace phipo = phipo +p3_6_1 if ((p3_2_1==1|p3_2_1==2) & p3_6_1>0 & p3_6_1~=.);

replace phipo = phipo +p3_6_2 if ((p3_2_2==1| p3_2_2==2) & p3_6_2>0 & p3_6_2~=.);

replace phipo = phipo +p3_6_3 if ((p3_2_3==1| p3_2_3==2)  & p3_6_3>0 & p3_6_3~=.);

replace phipo = phipo +p3_6_4 if ((p3_2_4==1| p3_2_4==2) & p3_6_4>0 & p3_6_4~=.);

replace phipo = phipo +p3_6_5 if ((p3_2_5==1| p3_2_5==2) & p3_6_5>0 & p3_6_5~=.);

replace phipo = phipo +p3_6_6 if ((p3_2_6==1| p3_2_6==2) & p3_6_6>0 & p3_6_6~=.);

replace phipo = phipo +p3_6_7 if ((p3_2_7==1| p3_2_7==2) & p3_6_7>0 & p3_6_7~=.);

replace phipo = phipo +p3_6_8 if ((p3_2_8==1| p3_2_8==2) & p3_6_8>0 & p3_6_8~=.);

rename phipo vmortgoth;
label var vmortgoth "value of outstanding mortgages for other purposes";

*Variable capturing any kind of mortgage or secure debt ;
gen mortgage =0;
replace mortgage=1 if mortgoth==1 | mortgmresid==1;

*DEUDAS PENDIENTES DE PRESTAMOS PERSONALES;
*OUTSTANDING DEBTS FROM PERSONAL LOANS;

*Para calcular la proporción de hogares que tienen deudas pendientes por prestamos personales generamos una nueva variable;
*To obtain the percentage of households that have outstanding debts from personal loans we generate a new variable;

gen perso=(p3_2_1==3| p3_2_2==3| p3_2_3==3| p3_2_4==3|p3_2_5==3| p3_2_6==3| p3_2_7==3| p3_2_8==3);
rename perso personal;
label var personal "have outstanding debts from personal loans";

*Para calcular el valor de las deudas pendientes por prestamos personales generamos una nueva variable;
*To obtain the value of the outstanding debts from personal loans we generate a new variable;

gen pperso=0;

replace pperso = pperso +p3_6_1 if (p3_2_1==3 & p3_6_1>0 & p3_6_1~=.);

replace pperso = pperso +p3_6_2 if (p3_2_2==3 & p3_6_2>0 & p3_6_2~=.);

replace pperso = pperso +p3_6_3 if (p3_2_3==3 & p3_6_3>0 & p3_6_3~=.);

replace pperso = pperso +p3_6_4 if (p3_2_4==3 & p3_6_4>0 & p3_6_4~=.);

replace pperso = pperso +p3_6_5 if (p3_2_5==3 & p3_6_5>0 & p3_6_5~=.);

replace pperso = pperso +p3_6_6 if (p3_2_6==3 & p3_6_6>0 & p3_6_6~=.);

replace pperso = pperso +p3_6_7 if (p3_2_7==3 & p3_6_7>0 & p3_6_7~=.);

replace pperso = pperso +p3_6_8 if (p3_2_8==3 & p3_6_8>0 & p3_6_8~=.);

rename pperso vpersonal;
label var vpersonal "value of personal loans";


*DEUDAS PENDIENTES CON TARJETAS DE CREDITO;
*OUTSTANDING CREDIT CARD BALANCES;

*Para calcular la proporción de hogares que tienen deudas pendientes con tarjetas de credito generamos una nueva variable;
*To obtain the percentage of households that have outstanding credit card balances we generate a new variable;

gen deuda_tarj=(p8_5a>0 & p8_5a~=.);
rename deuda_tarj credcard;
label var credcard "have outstanding credit card balances";

*Para calcular el valor de las deudas pendientes con tarjetas de credito generamos una nueva variable;
*To obtain the value of outstanding credit card balances we generate a new variable;

gen ptmos_tarj=0;

replace ptmos_tarj= p8_5a if (p8_5a>0 & p8_5a~=.);
rename ptmos_tarj vcredcard;
label var vcredcard "value of outstanding credit card balances";



*OTRAS DEUDAS;
*OTHER DEBTS;

*Para calcular la proporción de hogares que tienen otras deudas pendientes generamos una nueva variable;
*To obtain the percentage of households that have other outstanding debts we generate a new variable;

gen otrasd=(p3_2_1==4| p3_2_2==4| p3_2_3==4| p3_2_4==4| p3_2_5==4| p3_2_6==4| p3_2_7==4| p3_2_8==4|p3_2_1==5| p3_2_2==5| p3_2_3==5| p3_2_4==5| p3_2_5==5|
 p3_2_6==5| p3_2_7==5| p3_2_8==5| p3_2_1==6| p3_2_2==6| p3_2_3==6| p3_2_4==6| p3_2_5==6| p3_2_6==6| p3_2_7==6| p3_2_8==6| p3_2_1==7| p3_2_2==7| p3_2_3==7|
 p3_2_4==7| p3_2_5==7| p3_2_6==7| p3_2_7==7| p3_2_8==7| p3_2_1==8| p3_2_2==8| p3_2_3==8| p3_2_4==8| p3_2_5==8| p3_2_6==8| p3_2_7==8| p3_2_8==8| p3_2_1==9|
 p3_2_2==9| p3_2_3==9| p3_2_4==9| p3_2_5==9| p3_2_6==9| p3_2_7==9| p3_2_8==9| p3_2_1==97| p3_2_2==97| p3_2_3==97| p3_2_4==97 | p3_2_5==97| p3_2_6==97| 
 p3_2_7==97| p3_2_8==97);
rename otrasd othdebt;
label var othdebt "households that have other outstanding debt";


*Para calcular el valor de las otras deudas pendientes generamos una nueva variable;
*To obtain the value of the other outstanding debts we generate a new variable;

gen potrasd =0;

replace potrasd = potrasd +p3_6_1 if ((p3_2_1==4| p3_2_1==5| p3_2_1==6| p3_2_1==7| p3_2_1==8|p3_2_1==9|
p3_2_1==97) & p3_6_1>0 & p3_6_1~=.);

replace potrasd = potrasd +p3_6_2 if ((p3_2_2==4| p3_2_2==5|  p3_2_2==6| p3_2_2==7| p3_2_2==8|p3_2_2==9|
p3_2_2==97) & p3_6_2>0 & p3_6_2~=.);

replace potrasd = potrasd +p3_6_3 if ((p3_2_3==4| p3_2_3==5| p3_2_3==6| p3_2_3==7| p3_2_3==8|p3_2_3==9|
p3_2_3==97) & p3_6_3>0 & p3_6_3~=.);

replace potrasd = potrasd +p3_6_4 if ((p3_2_4==4| p3_2_4==5| p3_2_4==6| p3_2_4==7| p3_2_4==8|p3_2_4==9|
p3_2_4==97) & p3_6_4>0 & p3_6_4~=.);

replace potrasd = potrasd +p3_6_5 if ((p3_2_5==4| p3_2_5==5| p3_2_5==6| p3_2_5==7| p3_2_5==8|p3_2_5==9|
p3_2_5==97) & p3_6_5>0 & p3_6_5~=.);

replace potrasd = potrasd +p3_6_6 if ((p3_2_6==4| p3_2_6==5| p3_2_6==6| p3_2_6==7| p3_2_6==8|p3_2_6==9|
p3_2_6==97) & p3_6_6>0 & p3_6_6~=.);

replace potrasd = potrasd +p3_6_7 if ((p3_2_7==4| p3_2_7==5| p3_2_7==6| p3_2_7==7| p3_2_7==8|p3_2_7==9|
p3_2_7==97) & p3_6_7>0 & p3_6_7~=.);

replace potrasd = potrasd +p3_6_8 if ((p3_2_8==4| p3_2_8==5| p3_2_8==6| p3_2_8==7| p3_2_8==8|p3_2_8==9|
p3_2_8==97) & p3_6_8>0 & p3_6_8~=.);

rename potrasd vothdebt;
label var vothdebt "value of the other outstanding debts";


******************************************************************************************************;
******************************************************************************************************;

*                          R A N K I N G     A: NATURE OF THE DEBT									 *;

******************************************************************************************************;
******************************************************************************************************;
gen housesec=0;
gen houseunsec=0;
gen othsecured=0;
gen consumer=0;
gen rest=0;

gen vhousesec=0;
gen vhouseunsec=0;
gen vothsecured=0;
gen vconsumer=0;
gen vrest=0;

replace vhousesec=vhousesec+p2_55_4 if p2_55_4!=. /*Consider as secured, all debts attached to fourth real state properties in advanced */;

forvalues i=1(1)4 {;
replace housesec=1 if p2_9_`i'<=2;
replace vhousesec=vhousesec+p2_12_`i' if p2_9_`i'<=2; 
replace houseunsec=1 if p2_9_`i'>2 & p2_9_`i'<=97;
replace vhouseunsec=vhouseunsec+p2_12_`i' if p2_9_`i'>2 & p2_9_`i'<=97;
};

forvalues i=1(1)3 {;
		forvalues s=1(1)3 {; 
		replace housesec=1 if p2_52_`i'_`s'<=2;
		replace vhousesec=vhousesec+p2_55_`i'_`s' if  p2_52_`i'_`s'<=2;
		replace houseunsec=1 if p2_52_`i'_`s'>2 & p2_52_`i'_`s'<=97;
		replace vhouseunsec=vhousesec+p2_55_`i'_`s' if  p2_52_`i'_`s'>2 & p2_52_`i'_`s'<=97;
};
};

forvalues i=1(1)8 {;
replace othsecured=1 if p3_2_`i'<=2;
replace vothsecured=vothsecured+p3_6_`i' if p3_2_`i'<=2;
replace consumer=1 if p3_2_`i'==3;
replace vconsumer=vconsumer+p3_6_`i' if p3_2_`i'==3;
replace rest=1 if p3_2_`i'>3 & p3_2_`i'<=97;
replace vrest=vrest+p3_6_`i' if p3_2_`i'>3 & p3_2_`i'<=97;

};

******************************************************************************************************;
******************************************************************************************************;

*                          R A N K I N G     B: OBJECTIVE OF THE DEBT (housing comprises just secured loans. 'Rest' comprises housing unsecured;							 *;

******************************************************************************************************;
******************************************************************************************************;

gen housing=0;
*gen carloan=0;
gen busloan=0;
gen restbis=0;

replace housing=1 if housesec==1;
replace restbis=1 if houseunsec==1;
forvalues i=1(1)8 {;
*replace carloan=1 if p3_3_`i'==2;
replace busloan=1 if p3_3_`i'==12;
replace housing=1 if p3_3_`i'==14 & p3_2_`i'<=2;
replace restbis=1 if p3_3_`i'==1 | p3_3_`i'==2 | p3_3_`i'==3 | p3_3_`i'==4 | p3_3_`i'==34 | p3_3_`i'==5 | p3_3_`i'==6 | p3_3_`i'==7 | p3_3_`i'==8 | p3_3_`i'==9 |
						p3_3_`i'==10 | p3_3_`i'==11 | p3_3_`i'==13 | (p3_3_`i'==14 & p3_2_`i'>2) | p3_3_`i'==15 | p3_3_`i'==97;
						

};

gen vhousing=0;
*gen vcarloan=0;
gen vbusloan=0;
gen vrestbis=0;

replace vhousing=vhousesec;
replace vrestbis=vhouseunsec;
forvalues i=1(1)8 {;
*replace vcarloan=vcarloan + p3_6_`i' if p3_3_`i'==2;
replace vbusloan=vbusloan + p3_6_`i'  if p3_3_`i'==12;
replace vhousing=vhousing + p3_6_`i' if p3_3_`i'==14 & p3_2_`i'<=2;
replace vrestbis=vrestbis + p3_6_`i' if p3_3_`i'==1 | p3_3_`i'==2 | p3_3_`i'==3 | p3_3_`i'==4 | p3_3_`i'==34 | p3_3_`i'==5 | p3_3_`i'==6 | p3_3_`i'==7 | p3_3_`i'==8 | p3_3_`i'==9 |
						p3_3_`i'==10 | p3_3_`i'==11 | p3_3_`i'==13 | (p3_3_`i'==14 & p3_2_`i'>2) | p3_3_`i'==15 | p3_3_`i'==97;
};
 ******************* INTEREST RATES *************************;
* Main residence;
forvalues i=1(1)4{;
*rename p2_9_`i' loantypemresid_`i' /* 1-mortgage, 2- othsecured, 3- personal, 4- credit line, 5- deferred, 6- advances, 7- friends family, 97- other, 98- don't know missing */;
rename p2_13_`i' loanratemresid_`i';
rename p2_14_`i' loanfixmresid_`i';
replace loanfixmresid_`i'=1 if loanfixmresid_`i'==22;
replace loanfixmresid_`i'=0 if loanfixmresid_`i'==11;
};

* Other properties (up to 3 additional properties and 3 loans for each one);
forvalues a=1(1)3{ /*property*/;
forvalues i=1(1)3{ /*loan*/;

*rename p2_52_`a'_`i' loantypeothprop_`a'_`i' /* 1-mortgage, 2- othsecured, 3- personal, 4- credit line, 5- deferred, 6- advances, 7- friends family, 97- other, 98- don't know missing */;
rename p2_56_`a'_`i' loanrateothprop_`a'_`i';
rename p2_57_`a'_`i' loanfixothprop_`a'_`i';
replace loanfixothprop_`a'_`i'=1 if loanfixothprop_`a'_`i'==22;
replace loanfixothprop_`a'_`i'=0 if loanfixothprop_`a'_`i'==11;
};
};


* Other loans;
forvalues i=1(1)8{;
*rename p3_2_`i' loantypeother_`i' /* 1-mortgage, 2- othsecured, 3- personal, 4- credit line, 5- deferred, 6- advances, 7- friends family, 97- other, 98- don't know missing */;
rename p3_7_`i' loanrateother_`i';
rename p3_8_`i' loanfixother_`i';
replace loanfixother_`i'=1 if loanfixother_`i'==22;
replace loanfixother_`i'=0 if loanfixother_`i'==11;
};

* Credit card;
rename p8_5c int_credcard;

*************************** INTEREST RATES *******************************;
******* Housing ********;
gen int_housing=0;
forvalues i=1(1)4{;
replace int_housing=int_housing+loanratemresid_`i'*p2_12_`i' if p2_9_`i'<=2; 
};

forvalues a=1(1)3 {;
forvalues i=1(1)3 {;
replace int_housing=int_housing+loanrateothprop_`a'_`i'*p2_55_`a'_`i' if  p2_52_`a'_`i'<=2;
};
};

forvalues i=1(1)8{;
replace int_housing=int_housing+loanrateother_`i'*p3_6_`i' if p3_3_`i'==14 & p3_2_`i'<=2;
};
replace p2_55_4=0 if p2_55_4==.;
replace int_housing=int_housing/(vhousing-p2_55_4);

******** Business *******;
gen int_busloan=0;
forvalues i=1(1)8{;
replace int_busloan=int_busloan+loanrateother_`i'*p3_6_`i' if p3_3_`i'==12;
};

replace int_busloan=int_busloan/vbusloan;

********* Other *********;
gen int_restbis=0;
forvalues i=1(1)4{;
replace int_restbis=int_restbis+loanratemresid_`i'*p2_12_`i' if p2_9_`i'>2 & p2_9_`i'<=97; 
};

forvalues a=1(1)3 {;
forvalues i=1(1)3 {;
replace int_restbis=int_restbis+loanrateothprop_`a'_`i'*p2_55_`a'_`i' if  p2_52_`a'_`i'>2 & p2_52_`a'_`i'<=97;
};
};

forvalues i=1(1)8{;
replace int_restbis=int_restbis+loanrateother_`i'*p3_6_`i' if p3_3_`i'==1 | p3_3_`i'==2 | p3_3_`i'==3 | p3_3_`i'==4 | p3_3_`i'==34 | p3_3_`i'==5 | p3_3_`i'==6 | p3_3_`i'==7 | p3_3_`i'==8 | p3_3_`i'==9 |
						p3_3_`i'==10 | p3_3_`i'==11 | p3_3_`i'==13 | (p3_3_`i'==14 & p3_2_`i'>2) | p3_3_`i'==15 | p3_3_`i'==97;
};

replace int_restbis=int_restbis/vrestbis;

*************** Debt Portfolio Structure ***************;
/* Housing (debt 1), busloan (portfdebt2), Credcard (debt 3), Rest (debt 4)*/; 


******* ONE DEBT ********************************************************************;
gen portfdebt1=0;
replace portfdebt1=1 if housing==1 & busloan==0 & credcard==0 & restbis==0;

gen portfdebt2=0;
replace portfdebt2=1 if housing==0 & busloan==1 & credcard==0 & restbis==0;

					
gen portfdebt3=0;
replace portfdebt3=1 if housing==0 & busloan==0 & credcard==1 & restbis==0;

gen portfdebt4=0;
replace portfdebt4=1 if housing==0 & busloan==0 & credcard==0 & restbis==1;


******* TWO DEBTS ********************************************************************;
gen portfdebt12=0;
replace portfdebt12=1 if housing==1 & busloan==1 & credcard==0 & restbis==0;

gen portfdebt13=0;
replace portfdebt13=1 if housing==1 & busloan==0 & credcard==1 & restbis==0;

gen portfdebt14=0;
replace portfdebt14=1  if housing==1 & busloan==0 & credcard==0 & restbis==1;

gen portfdebt23=0;
replace portfdebt23=1  if housing==0 & busloan==1 & credcard==1 & restbis==0;

gen portfdebt24=0;
replace portfdebt24=1  if housing==0 & busloan==1 & credcard==0 & restbis==1;


gen portfdebt34=0;
replace portfdebt34=1  if housing==0 & busloan==0 & credcard==1 & restbis==1;


**********THREE DEBTS ********************************************************************;
gen portfdebt123=0;
replace portfdebt123=1  if housing==1 & busloan==1 & credcard==1 & restbis==0;

gen portfdebt124=0;
replace portfdebt124=1  if housing==1 & busloan==1 & credcard==0 & restbis==1;

gen portfdebt134=0;
replace portfdebt134=1  if housing==1 & busloan==0 & credcard==1 & restbis==1;

gen portfdebt234=0;
replace portfdebt234=1  if housing==0 & busloan==1 & credcard==1 & restbis==1;

********* FOUR DEBTS *********************************************************************;
gen portfdebt1234=0;
replace portfdebt1234=1  if housing==1 & busloan==1 & credcard==1 & restbis==1;


*ALGUN TIPO DE DEUDA PENDIENTE;
*SOME TYPE OF OUTSTANDING DEBT;

*Para calcular la proporción de hogares que tienen algún tipo de deuda pendiente generamos una nueva variable;
*To obtain the percentage of households that have some type of outstanding debt we generate a new variable;

gen adeuda= (debtmresid==1| debtothprop==1| p3_1>0 | credcard==1);
rename adeuda anydebt;
label var anydebt "have some type of outstanding debt";

*Para calcular el valor de las deudas pendientes generamos una nueva variable;
*To obtain the value of the outstanding debt we generate a new variable;

gen vdeuda= vdebtmresid + vdebtothprop+ vmortgoth+ vpersonal+ vothdebt + vcredcard;
rename vdeuda vdebt;
label var vdebt "value of the outstanding debt";

foreach var in portfdebt1 portfdebt2 portfdebt3 portfdebt4 portfdebt12 portfdebt13 portfdebt14 portfdebt23 
 portfdebt24 portfdebt34 portfdebt123 portfdebt124 portfdebt134 portfdebt234 portfdebt1234 {;
 
 gen v`var'=.;
 replace v`var'=vdebt if `var'==1;
 
 };
 

*VARIABLES DE RIQUEZA TOTAL Y RIQUEZAS INTERMEDIAS;
*TOTAL AND INTERMEDIATE WEALTH VARIABLES;


*ACTIVOS REALES;
*REAL ASSETS;

gen actreales=0;
replace actreales=actreales+vmresid if (vmresid>0 & vmresid~=.);
replace actreales=actreales+vothprop;
replace actreales=actreales+vjewel if (vjewel>0 & vjewel~=.);
replace actreales=actreales+valhog;

rename actreales rassets;
label var rassets "Value of real assets";

*ACTIVOS FINANCIEROS;
*FINANCIAL ASSETS;

gen actfinanc=0;
replace actfinanc=actfinanc+vaccount_pay if (vaccount_pay>0 & vaccount_pay~=.);
replace actfinanc=actfinanc+vlistshare if (vlistshare>0 & vlistshare~=.);
replace actfinanc=actfinanc+vunlist if (vunlist>0 & vunlist~=.);
replace actfinanc=actfinanc+vfixsec if (vfixsec>0 & vfixsec~=.);
replace actfinanc=actfinanc+allf if (allf>0 & allf~=.);
replace actfinanc=actfinanc+vaccount_nopay;
replace actfinanc=actfinanc+vpenplan;
replace actfinanc=actfinanc+vlifeinsur;
replace actfinanc=actfinanc+vcreditor;

rename actfinanc fassets;
label var fassets "Value of financial assets";

*RIQUEZA BRUTA;
*GROSS WEALTH;

gen riquezabr=0;
replace riquezabr=riquezabr+rassets+fassets;

rename riquezabr gwealth;
label var gwealth "Gross Wealth";

*RIQUEZA NETA=RIQUEZA BRUTA-DEUDAS;
*NET WEALTH=GROSS WEALTH-DEBTS;

gen riquezanet=gwealth-vdebt;
rename riquezanet nwealth;
label var nwealth "Net Wealth";

*CUADRO 6: VALOR TIPOS DE DEUDA SEGUN OBJETIVO DE LA DEUDA;
*TABLE 6: VALUE OF DEBTS BY PURPOSE OF DEBTS;

*TBD;

*Para deuda por compra vivienda principal usamos dvivpral;
*For debt originated by home purchase we use dvivpral;

*Para deuda por compra otras prop. inmobiliarias usamos deuoprop;
*For debt originated by purchase of other real estate properties we use deuoprop;

*Para deudas pendientes por el resto de deudas (garantia real, credito personal, otras deudas, deudas con tarjetas de credito) usaremos deuotros;
*For other outstanding debts (secured loans, personal loans, credit card balances and other debts) we use deuotros;

*CUADRO 8: RATIOS INDIVIDUALES DE DEUDA;
*TABLE 8: INDIVIDUAL DEBT RATIOS;

*PAGOS POR DEUDAS;
*DEBT PAYMENTS;

*Para el total de pagos por deudas generamos la variable pagodeuda;
*For total debt payments we generate the variable pagodeuda;

gen pagodeuda=0;
gen pagodeuviv=0;
gen pagodeuoprop=0;
gen pagodeusec3=0;


set output error;
forvalues j=1/4 {;

	display _newline(1) `j';

	gen np2_18_`j'=p2_18_`j';
	replace np2_18_`j'=0 if (p2_18_`j'==.|p2_18_`j'<0);
	replace pagodeuviv=pagodeuviv+np2_18_`j';
	};

forvalues j=1/8 { ;
	
	display _newline(1) `j';
	gen np3_11_`j'=p3_11_`j';
	replace np3_11_`j'=0 if (p3_11_`j'==.|p3_11_`j'<0);
	replace pagodeusec3=pagodeusec3+np3_11_`j';	
	};

forvalues m=1/3   {;

	forvalues j=1/3 {;

	display _newline(1) `m' `j';
	
	gen np2_61_`m'_`j'=p2_61_`m'_`j';
	replace np2_61_`m'_`j'=0 if (p2_61_`m'_`j'==.|p2_61_`m'_`j'<0);
	replace pagodeuoprop=pagodeuoprop+np2_61_`m'_`j';
	};

};
set output proc;

gen np2_61_4=p2_61_4;
replace np2_61_4=0 if (p2_61_4==. | p2_61_4<0);
replace pagodeuoprop=pagodeuoprop+np2_61_4;

gen np8_5b=p8_5b;
replace np8_5b=0 if (p8_5b==. | p8_5b<0);
gen pagotarjeta=np8_5b;


replace pagodeuda=pagodeuviv+pagodeuoprop+pagodeusec3 + pagotarjeta;

rename pagodeuda paydebt;
label var paydebt "Monthly total debt payments";
rename pagodeuviv paydresid;
label var paydresid "Monthly residential debt payments";
rename pagodeuoprop payothprop;
label var payothprop "Monthly other properties debt payments";
rename pagodeusec3 paypersonal;
label var paypersonal "Monthly personal debt payments";

*CUADRO 9: GASTO EN BIENES DURADEROS Y NO DURADEROS Y TENENCIA DE BIENES DURADEROS;
*TABLE 9: EXPENDITURE ON NON-DURABLE AND DURABLE GOODS AND HOLDINGS OF DURABLE GOODS;

*1.-GASTO ANUAL BIENES VARIOS (% y mediana);
*1.-ANNUAL EXPENDITURE ON DIFFERENT GOODS (% and median);

*Gasto anual en Alimentacion;
*Annual expenditure on Food;

gen frec=12 if p9_2b==2;
replace frec=12*4.3 if p9_2b==1;
gen alim=0;
replace alim=alim+(p9_2*frec) if p9_2>0;
rename alim food;
label var food "Annual expenditure on Food";

*Gasto anual en Otros bienes no duraderos;
*Annual expenditure on Other non-durable goods;

gen nodur=0;
replace nodur=nodur+ (p9_1*12)-food if p9_1>0;
label var nodur "Annual expenditure on Other non-durable goods";

*Gasto anual en vehiculos (si/no y valor);
*Annual expenditure on vehicles (yes/no and value);

*Para decisión adquisición vehículos;
*For the decision to buy vehicles;

gen gvehic=(p2_73==1 | p2_77==1);
rename gvehic vehic;
label var vehic "household purchased a vehicle that year";

*Para valor adquisicion vehículos;
*For the value of vehicles purchased;

gen gimpvehic=0;
replace gimpvehic=gimpvehic+p2_74 if (p2_74>0 & p2_74~=.);
replace gimpvehic=gimpvehic+p2_78 if (p2_78>0 & p2_78~=.);
rename gimpvehic vvehicle;
label var vvehicle "value of vehicles purchased";

*Gasto anual en Otros bienes duraderos (si/no y valor);
*Annual expenditure on Other durable goods (yes/no and value);


*Para decisión adquisición bienes duraderos utilizamos la p2_69;
*For the decision to buy durable goods we use the variable p2_69;

*Para valor adquisicion bienes duraderos usamos p2_70;
*For the value of durable goods purchases we use p2_70;


*2.- PARA TENENCIA DURADEROS (% Y MEDIANA);
*2.- FOR HOLDINGS OF DURABLE GOODS (% AND MEDIAN);

*Tenencia vehiculos;
*Holding of vehicles;

*Proporcion con vehiculos;
*Percentage with vehicles;

gen tvehic=(p2_72>0|p2_76>0);

*Mediana para los que tienen;
*Median for the ones who have; 

gen timpvehic=0;
replace timpvehic = timpvehic + p2_75 if (p2_72>0 & p2_75>0 & p2_75~=.);
replace timpvehic = timpvehic + p2_79 if ( p2_76>0 &  p2_79>0 & p2_79~=.);

*Tenencia Otros bienes duraderos;
*Holding of Other durable goods;

*Para valor tenencia bienes duraderos usamos p2_71;
*For the value of durable goods holdings we use p2_71;


*VARIABLES DE CARACTERISTICAS DE LOS HOGARES QUE FIGURAN EN LOS CUADROS;
*VARIABLES OF HOUSEHOLD CHARACTERISTICS THAT APPEAR IN THE TABLES;

*1.- DEFINICIÓN DE PERCENTILES (i) RENTA TOTAL HOGAR Y (ii) RIQUEZA NETA;
*1.- DEFINITION OF PERCENTILES (i) HOUSEHOLD TOTAL INCOME AND (ii) NET WEALTH; 
rename renthog hhincome /* annual 2001 for 2002 wave, 2004 (2005 wave), 2007 (2008 wave) */;
_pctile hhincome [pweight=facine3], p(20,40,60,80,90);
return list;

gen percrent=1 if (hhincome<r(r1));
replace percrent=2 if (hhincome>=r(r1) & hhincome<r(r2));
replace percrent=3 if (hhincome>=r(r2) & hhincome<r(r3));
replace percrent=4 if (hhincome>=r(r3) & hhincome<r(r4));
replace percrent=5 if (hhincome>=r(r4) & hhincome<r(r5));
replace percrent=6 if  hhincome>=r(r5);


_pctile nwealth [pweight=facine3], p(25,50,75,90);
return list;

gen percriq=1 if (nwealth<r(r1));
replace percriq=2 if (nwealth>=r(r1) & nwealth<r(r2));
replace percriq=3 if (nwealth>=r(r2) & nwealth<r(r3));
replace percriq=4 if (nwealth>=r(r3) & nwealth<r(r4));
replace percriq=5 if  nwealth>=r(r4);

gen percriq25=1 if nwealth==r(r1);
gen percriq50=1 if nwealth==r(r2);
gen percriq75=1 if nwealth==r(r3);



*2.- NOMBRE Y CODIFICACIÓN DE LAS VARIABLES QUE RECOGEN CARACTERÍSTICAS SOCIO-DEMOGRÁFICAS DEL HOGAR QUE APARECEN EN LOS CUADROS;
*2.- NAME AND CODING OF THE VARIABLES THAT CONTAIN HOUSEHOLDS SOCIO-DEMOGRAPHIC CHARACTERISTICS THAT APPEAR IN THE TABLES;

*EDAD DEL CABEZA DE FAMILIA;
*AGE OF HOUSEHOLD HEAD;
*bage: toma valores 1 a 6, <35, >34 & <45, >44 & <55, >54 & <65, >64 & <75, >74;
*bage: takes values 1 to 6, <35, >34 & <45, >44 & <55, >54 & <65, >64 & <75, >74;

*SITUACION LABORAL DEL CABEZA DE FAMILIA;
*LABOUR MARKET SITUATION OF HOUSEHOLD HEAD;
*nsitlabdom: toma valores 1 a 4, empleado por cuenta ajena, empleado por cuenta propia, jubilado, otro tipo de inactivo o parado;
*nsitlabdom: takes values 1 to 4, employee, self-employed, retired, other type of economic inactivity or unemployed;

*NIVEL DE EDUCACION DEL CABEZA DE FAMILIA;
*LEVEL OF EDUCATION OF HOUSEHOLD HEAD;
*neducdom: toma valores 1 a 3, inferior a bachillerato, bachillerato, estudios universitarios;
*neducdom: takes values 1 to 3, below secondary education, secondary education, University education;

*REGIMEN DE TENENCIA DE LA VIVIENDA PRINCIPAL;
*STATUS OF MAIN RESIDENCE;
*np2_1: toma valores 1 y 0, propiedad, otros regímenes de tenencia;
*np2_1: takes values 1 and 0, ownership, other;


*NUMERO DE ADULTOS EN EL HOGAR TRABAJANDO;
*NUMBER OF ADULT HOUSEHOLD MEMBERS WORKING;
*nnumadtrab: toma valores 0 a 3, ninguno, uno, dos, tres o más;
*nnumadtrab: takes values 0 to 3, none, one, two, three or more;


*NUMERO DE MIEMBROS EN EL HOGAR;
*NUMBER OF HOUSEHOLD MEMBERS;
*np1: toma valores 1 a 5, uno, dos, tres, cuatro, cinco o más.
*np1: takes values 1 to 5, one, two, three, four, five or more.


**** Reference person (designed by the household) variables ****;
/* From questionnaire: "The reference person is the person, or one of the persons, responsible for the accommodation. It will normally be the person in the 
household who chiefly deals with the financial issues." */;

rename p1 members /* Number of household members */;




forvalues i = 1(1)9 {;
	rename p1_1_`i' sex`i' /* Male (1), Female (0)*/;
	replace sex`i'=0 if sex`i'==2;
	rename p1_2b_`i' nac`i';
	rename p1_3_`i' relref`i';
	rename p1_5_`i' educ`i' /* Education level (see questionnaire)*/;
	rename p1_7_`i' health`i' /* Health status of reference person: 1-very good, 2-good, 3-acceptable, 4-poor, 5-very poor */;
	rename p6_1c1_`i' employee`i';
	rename p6_1c2_`i' selfemployed`i';
	rename p6_1c3_`i' unemployed`i';
	rename p6_1c4_`i' retiree`i';
	rename p6_1c5_`i' disable`i';
	rename p6_1c6_`i' student`i';
	rename p6_1c7_`i' housew`i';
	rename p6_1c8_`i' oth_inact`i';
	rename p6_4_`i' typejob`i';
	gen bankjob`i'=0;
	replace bankjob`i'=1 if typejob`i'==9;
	};

	forvalues i = 1(1)9 {;
	gen ageaux`i'=0;
	replace ageaux`i'=2005-nac`i';
	gen child`i'=0;
	replace child`i'=1 if ageaux`i'<16 ;
	};

cap drop ageaux*;

egen nchilds=rowtotal(child1-child9);
	
gen sex=0;
gen nac=0;
gen educ=0;
gen health=0;
gen employee=0;
gen selfemployed=0;
gen unemployed=0;
gen retiree=0;
gen disable=0;
gen student=0;
gen housew=0;
gen oth_inact=0;
gen bankjob=0;

* Dummy variable for university degree;
* Ordinary university degree / Training leading to an officially recognised professional specialisation;
* Postgraduate university education ;

forvalues i = 1(1)9 {;
gen univ`i'=0;
replace univ`i'=1 if educ`i'==10 | educ`i'==11 | educ`i'==12;
};

gen univ=0;


/* Marital status reference person: married if any other person in the household declares to be the couple of the head */;

gen married=0;

forvalues i = 2(1)9 {;
	replace married=1 if relref`i'==2;
	};

gen couplewith=(married==1 & nchilds>0);
gen couplewithout=(married==1 & nchilds==0);
gen singlewith=(married==0 & nchilds>0);
gen singlewithout=(married==0 & nchilds==0);	
	
rename p1_4_1 marital1 /* Marital status reference person: 1-single, 2-married, 3-de facto partner 
						4-separated, 5-divorced, 6-widowed */;

/* With the information of the other members, create variables that summarize the familiar characteristics */;

*gen othcoup=0 /* to identify those hh where household head is not the reference person in the survey */;

*CRITERIUM: Take the main earner in employees. Otherwise, take the male;

* Compute wage for each member of the houysehold;
forvalues i=1(1)9{;
replace student`i'=0 if oth_inact`i'==1 | disable`i'==1 | housew`i'==1 | unemployed`i'==1 | retiree`i'==1 | selfemployed`i'==1 | employee`i'==1;
replace oth_inact`i'=0 if disable`i'==1 | housew`i'==1 | unemployed`i'==1 | retiree`i'==1 | selfemployed`i'==1 | employee`i'==1;
replace disable`i'=0 if housew`i'==1 | unemployed`i'==1 | retiree`i'==1 | selfemployed`i'==1 | employee`i'==1;
replace housew`i'=0 if unemployed`i'==1 | retiree`i'==1 | selfemployed`i'==1 | employee`i'==1;
replace unemployed`i'=0 if retiree`i'==1 | selfemployed`i'==1 | employee`i'==1;
replace retiree`i'=0 if selfemployed`i'==1 | employee`i'==1;
replace selfemployed`i'=0 if employee`i'==1;
gen ageaux`i'=0;
replace ageaux`i'=2005-nac`i';
replace retiree`i'=1 if (housew`i'==1 | oth_inact`i'==1 | disable`i'==1 | student`i'==1) & ageaux`i'>=65 /* Take this persons as retired */;
replace housew`i'=0 if retiree`i'==1;
replace oth_inact`i'=0 if retiree`i'==1;
replace disable`i'=0 if retiree`i'==1;
replace student`i'=0 if retiree`i'==1;
};

forvalues i=1(1)9{;
	egen wage`i'=rowtotal(p6_14_`i'_*);
	gen mainearner`i'=0;
		replace employee`i'=1 if wage`i'>0 & student`i'==0 & oth_inact`i'==0 & disable`i'==0 & housew`i'==0 & 
	unemployed`i'==0 & retiree`i'==0 & selfemployed`i'==0 & employee`i'==0;
	};
	
replace mainearner1=1;

forvalues i=2(1)9{;
	replace mainearner`i'=1 if wage`i'>wage1 & relref`i'==2 & employee`i'==1;
	replace mainearner1=0   if wage`i'>wage1 & relref`i'==2 & employee`i'==1;	
	};	

forvalues i =2(1)9 {;
	gen othcoup`i'=0;
	replace othcoup`i'=1 if married==1 & sex1==0 & sex`i'==1 & relref`i'==2;	
	replace othcoup`i'=1 if married==1 & mainearner`i'==1 & relref`i'==2;
	replace othcoup`i'=1 if married==1 & (housew==1 | student==1) & 
		(unemployed`i'==1 | retiree`i'==1 | selfemployed`i'==1) & relref`i'==2 /*Take the couple when head is housewife */;
	replace sex=sex`i' if othcoup`i'==1;
	replace nac=nac`i' if othcoup`i'==1;
	replace educ=educ`i' if othcoup`i'==1;
	replace health=health`i' if othcoup`i'==1;
	replace employee=employee`i' if othcoup`i'==1;
	replace selfemployed=selfemployed`i' if othcoup`i'==1;
	replace unemployed=unemployed`i' if othcoup`i'==1;
	replace student=student`i' if othcoup`i'==1;
	replace housew=housew`i' if othcoup`i'==1;
	replace oth_inact=oth_inact`i' if othcoup`i'==1;
	replace retiree=retiree`i' if othcoup`i'==1;
	replace health=health`i' if othcoup`i'==1;
	replace univ=univ`i' if othcoup`i'==1;
	replace bankjob=bankjob`i' if othcoup`i'==1;
	};

egen othcoup=rowtotal(othcoup*);

replace sex=sex1 if othcoup==0;
replace nac=nac1 if othcoup==0;
replace educ=educ1 if othcoup==0;
replace health=health1 if othcoup==0;
replace employee=employee1 if othcoup==0;
replace selfemployed=selfemployed1 if othcoup==0;
replace retiree=retiree1 if othcoup==0;
replace disable=disable1 if othcoup==0;
replace student=student1 if othcoup==0;
replace housew=housew1 if othcoup==0;
replace oth_inact=oth_inact1 if othcoup==0;
replace unemployed=unemployed1 if othcoup==0;
replace univ=univ1 if othcoup==0;
replace bankjob=bankjob1 if othcoup==0;


/* Gen dummy to identify status of the couple */;
gen pemployee=0;
gen pselfemployed=0;
gen punemployed=0;
gen pretiree=0;
gen pdisable=0;
gen pstudent=0;
gen phousew=0;
gen poth_inact=0;
gen puniv=0;
gen pnac=0;

forvalues i=2(1)9 {;
	replace punemployed=1 if othcoup`i'==0 & unemployed`i'==1 & relref`i'==2;
	replace pemployee=1 if othcoup`i'==0 & employee`i'==1 & relref`i'==2;
	replace pretiree=1 if othcoup`i'==0 & retiree`i'==1 & relref`i'==2;
	replace pselfemployed=1 if othcoup`i'==0 & selfemployed`i'==1 & relref`i'==2;
	replace pdisable=1 if othcoup`i'==0 & disable`i'==1 & relref`i'==2;
	replace pstudent=1 if othcoup`i'==0 & student`i'==1 & relref`i'==2;
	replace phousew=1 if othcoup`i'==0 & housew`i'==1 & relref`i'==2;
	replace poth_inact=1 if othcoup`i'==0 & oth_inact`i'==1 & relref`i'==2;
	replace puniv=1 if othcoup`i'==0 & univ`i'==1 & relref`i'==2;
	replace pnac=1 if othcoup`i'==0 & nac`i'==1 & relref`i'==2;

	replace punemployed=1 if othcoup`i'==1 & unemployed1==1 & relref`i'==2;
	replace pemployee=1 if othcoup`i'==1 & employee1==1 & relref`i'==2;
	replace pretiree=1 if othcoup`i'==1 & retiree1==1 & relref`i'==2;
	replace pselfemployed=1 if othcoup`i'==1 & selfemployed1==1 & relref`i'==2;
	replace pdisable=1 if othcoup`i'==1 & disable1==1 & relref`i'==2;
	replace pstudent=1 if othcoup`i'==1 & student1==1 & relref`i'==2;
	replace phousew=1 if othcoup`i'==1 & housew1==1 & relref`i'==2;
	replace poth_inact=1 if othcoup`i'==1 & oth_inact1==1 & relref`i'==2;
	replace puniv=1 if othcoup`i'==1 & univ1==1 & relref`i'==2;
	replace pnac=1 if othcoup`i'==1 & nac1==1 & relref`i'==2;
	};
* Define other reference person for housew/student households: specifically, take as reference person those sons or daughters that are
main earners;

egen maxw=rowmax(wage1 wage2 wage3 wage4 wage5 wage6 wage7 wage8 wage9);

forvalues i=2(1)9{;
		gen oth_member`i'=0;
		replace oth_member`i'=1 if (housew==1 | student==1) & wage`i'==maxw & maxw>0;
		replace employee`i'=1 if oth_member`i'==1;
		replace sex=sex`i' if oth_member`i'==1;
		*replace psex=0 if oth_member`i'==1 /* Assume has no couple */;
		replace nac=nac`i' if oth_member`i'==1;
		replace pnac=0 if oth_member`i'==1 /* Assume has no couple */;
		replace educ=educ`i' if oth_member`i'==1;
		*replace peduc=0 if oth_member`i'==1 /* Assume has no couple */;
		replace health=health`i' if oth_member`i'==1;
		*replace phealth=0 if oth_member`i'==1 /* Assume has no couple */;
		replace employee=employee`i' if oth_member`i'==1;
		replace pemployee=0 if oth_member`i'==1 /* Assume has no couple */;
		replace selfemployed=selfemployed`i' if oth_member`i'==1;
		replace pselfemployed=0 if oth_member`i'==1 /* Assume has no couple */;
		replace retiree=retiree`i' if oth_member`i'==1;
		replace pretiree=0 if oth_member`i'==1 /* Assume has no couple */;
		replace disable=disable`i' if oth_member`i'==1;
		replace pdisable=0 if oth_member`i'==1 /* Assume has no couple */;
		replace student=student`i' if oth_member`i'==1;
		replace pstudent=0 if oth_member`i'==1 /* Assume has no couple */;
		replace housew=housew`i' if oth_member`i'==1;
		replace phousew=0 if oth_member`i'==1 /* Assume has no couple */;
		replace oth_inact=oth_inact`i' if oth_member`i'==1;
		replace poth_inact=0 if oth_member`i'==1 /* Assume has no couple */;
		replace unemployed=unemployed`i' if oth_member`i'==1;
		replace punemployed=0 if oth_member`i'==1 /* Assume has no couple */;
		replace univ=univ`i' if oth_member`i'==1;
		replace puniv=0 if oth_member`i'==1 /* Assume has no couple */;
		};	

egen auxoth=rowtotal(oth_member*);
		
/* Choose other household member if there are no employees*/;
forvalues i=2(1)9{;
		gen oth2_member`i'=0;
		replace oth2_member`i'=1 if (housew==1 | student==1) & auxoth==0 & selfemployed`i'==1;
		replace selfemployed`i'=1 if oth2_member`i'==1;
		replace sex=sex`i' if oth2_member`i'==1;
		*replace psex=0 if oth_member`i'==1 /* Assume has no couple */;
		replace nac=nac`i' if oth2_member`i'==1;
		replace pnac=0 if oth2_member`i'==1 /* Assume has no couple */;
		replace educ=educ`i' if oth2_member`i'==1;
		*replace peduc=0 if oth_member`i'==1 /* Assume has no couple */;
		replace health=health`i' if oth2_member`i'==1;
		*replace phealth=0 if oth_member`i'==1 /* Assume has no couple */;
		replace employee=employee`i' if oth2_member`i'==1;
		replace pemployee=0 if oth2_member`i'==1 /* Assume has no couple */;
		replace selfemployed=selfemployed`i' if oth2_member`i'==1;
		replace pselfemployed=0 if oth2_member`i'==1 /* Assume has no couple */;
		replace retiree=retiree`i' if oth2_member`i'==1;
		replace pretiree=0 if oth2_member`i'==1 /* Assume has no couple */;
		replace disable=disable`i' if oth2_member`i'==1;
		replace pdisable=0 if oth2_member`i'==1 /* Assume has no couple */;
		replace student=student`i' if oth2_member`i'==1;
		replace pstudent=0 if oth2_member`i'==1 /* Assume has no couple */;
		replace housew=housew`i' if oth2_member`i'==1;
		replace phousew=0 if oth2_member`i'==1 /* Assume has no couple */;
		replace oth_inact=oth_inact`i' if oth2_member`i'==1;
		replace poth_inact=0 if oth2_member`i'==1 /* Assume has no couple */;
		replace unemployed=unemployed`i' if oth2_member`i'==1;
		replace punemployed=0 if oth2_member`i'==1 /* Assume has no couple */;
		replace univ=univ`i' if oth2_member`i'==1;
		replace puniv=0 if oth2_member`i'==1 /* Assume has no couple */;
		};
		
gen bhealth=0;
replace bhealth=1 if health>=4;

egen auxoth2=rowtotal(oth2_member*);

egen aux=rowtotal(employee selfemployed unemployed retiree disable student housew oth_inact);
keep if aux==1;
gen age=2005-nac;
replace age=age/10;

** Age dummies **;
gen age1=0;
replace age1=1 if age>=3 & age<3.5;

gen age2=0;
replace age2=1 if age>=3.5 & age<4;

gen age3=0;
replace age3=1 if age>=4 & age<4.5;

gen age4=0;
replace age4=1 if age>=4.5 & age<5;

gen age5=0;
replace age5=1 if age>=5 & age<5.5;

gen age6=0;
replace age6=1 if age>=5.5 & age<6;

gen age7=0;
replace age7=1 if age>=6 & age<6.5;

gen age8=0;
replace age8=1 if age>=6.5 & age<7;

gen age9=0;
replace age9=1 if age>=7 & age<7.6;

gen age_inst=0;
replace age_inst=1 if age1==1;
replace age_inst=2 if age2==1;
replace age_inst=3 if age3==1;
replace age_inst=4 if age4==1;
replace age_inst=5 if age5==1;
replace age_inst=6 if age6==1;
replace age_inst=7 if age7==1;
replace age_inst=8 if age8==1;
replace age_inst=9 if age9==1;


gen agesq=age^2;

gen page=2005-nac;
replace page=page/10;

** page dummies **;
gen page1=0;
replace page1=1 if page>=3 & page<3.5;

gen page2=0;
replace page2=1 if page>=3.5 & page<4;

gen page3=0;
replace page3=1 if page>=4 & page<4.5;

gen page4=0;
replace page4=1 if page>=4.5 & page<5;

gen page5=0;
replace page5=1 if page>=5 & page<5.5;

gen page6=0;
replace page6=1 if page>=5.5 & page<6;

gen page7=0;
replace page7=1 if page>=6 & page<6.5;

gen page8=0;
replace page8=1 if page>=6.5 & page<7;

gen page9=0;
replace page9=1 if page>=7 & page<7.6;

gen page_inst=0;
replace page_inst=1 if page1==1;
replace page_inst=2 if page2==1;
replace page_inst=3 if page3==1;
replace page_inst=4 if page4==1;
replace page_inst=5 if page5==1;
replace page_inst=6 if page6==1;
replace page_inst=7 if page7==1;
replace page_inst=8 if page8==1;
replace page_inst=9 if page9==1;

gen pagesq=page^2;


/* Drop multiple-unrelated households */;

egen minval=rowmin(relref*);
replace minval=0 if minval==.;

gen madult=0;
replace madult=1 if minval==9 & (year==2002 | year==2005);
replace madult=1 if minval==12 & (year==2008 | year==2011);

  
		  ******************* Application for loans ********************;

rename p3_14 nreject /* number of applications rejected */;

/* Totally reject loan application (any) */;
gen reject=0;
replace reject=1 if nreject>0;
replace reject=0 if nreject==.;

forvalues i=1(1)5 {;
	rename p3_13s`i' rnoappl`i' /* Reasons of not applying for a loan */;
	rename p3_15s`i' rreject`i' /* Reasons of rejecting */;
	};

rename p3_12 napplic /* Number of no applications made in last two years */;

/* Discouraged borrowers: refuse to apply for a loan because it would be turned down (any member of the household. Exclude debt holders */;
gen discour=0;
replace discour=1 if (rnoappl1==4 | rnoappl2==4 | rnoappl3==4 | rnoappl4==4 | rnoappl5==4) & anydebt==0 & napplic==0;


/* Applicant: whether the household made any loan application or refused beacuse of sure rejecting */;
gen applic=0;
replace applic=1 if napplic>0 | discour==1 | anydebt==1;
* replace applic=0 if ration==0 & anydebt==0 /* Applied, accepted but did not take the loan (we think they took the loan and repaid the debt) */;

* gen applic_non_disc=0;
* replace applic_non_disc=1 if napplic>0 | anydebt==1;


rename p3_16 npartrej /* # times granted smaller amount than asked for */;



/* Partially rejected loan application (any) */;
gen partrej=0;
replace partrej=1 if npartrej>0;
replace partrej=0 if npartrej==.;

gen totpartrej=0;
replace totpartrej=1 if (reject==1 | partrej==1);
replace totpartrej=1 if discour==1;
*replace totpartrej=0 if anydebt==1;

/* Rationed: discouraged or reject totally or partially */;
gen ration2=0;
replace ration2=1 if discour==1 | partrej==1 | reject==1;
replace ration2=0 if ration2==.;
*replace ration2=0 if anydebt==1;

/* Rationed: discouraged or totally rejected */;
gen ration=0;
replace ration=1 if discour==1 | reject==1;
replace ration=0 if ration==.;
*replace ration=0 if anydebt==1;

*replace anydebt=1 if applic==1 & anydebt==0 & ration==0 /* Applied, borrowed and repaid, and report zero borrowing */;


/* Another definition is made 200 lines or more in advanced (guess that it was done in Venice)
/* Partially and Totally rationed */;

gen totpartrej=0;
replace totpartrej=1 if reject==1 | partrej==1;
*/;



**************** INCOME *********************;
replace hhincome=hhincome/acpi*100;
gen lincome=log(1+hhincome);
replace hhincome=hhincome/10000;
gen hhincomesq=(hhincome^2)/10000;

rename mrenthog mhhincome /* month oct2002 - may2003 (2002), nov2005 - may2006 (2005), nov2008 - jun2009 (2008) */;
replace mhhincome=mhhincome/mcpi*100;
gen mhhincomesq=mhhincome^2;


************** FINANCIAL HELP FROM RELATIVES AND FRIENDS *******************;
/*monetary assistance from friends or family members outside the
household, or from a partner no longer living in the household*/;

rename p6_59 finhelp;
replace finhelp=0 if finhelp==2;

rename p6_60 amounthelp;
replace amounthelp=amounthelp/mcpi*100;

************ ARREARS *****************;

/* In the last twelve months have you had any financial
difficulties which resulted in your delaying the payment of any of
your debts? */;

gen arrears=0;
replace arrears=1 if p9_16==1;

*replace anydebt=1 if arrears==1;
replace applic=1 if anydebt==1;
*replace ration=0 if arrears==1;
replace discour=0 if anydebt==1;

gen applic_non_disc=0;
replace applic_non_disc=1 if applic==1 & discour==0;

gen repay=.;
replace repay=1 if arrears==0 & anydebt==1;
replace repay=0 if arrears==1;

* Risk Aversion;
rename p9_11 riskaver;

gen risklot=.;
replace risklot=0 if riskaver==2 | riskaver==3 | riskaver==4;
replace risklot=1 if riskaver==1;

gen riskfair=.;
replace riskfair=0 if riskaver==1 | riskaver==3 | riskaver==4;
replace riskfair=1 if riskaver==2;

gen risksome=.;
replace risksome=0 if riskaver==1 | riskaver==2 | riskaver==4;
replace risksome=1 if riskaver==3;

gen norisk=.;
replace norisk=0 if riskaver==1 | riskaver==2 | riskaver==3;
replace norisk=1 if riskaver==4;

******** Dummies for hhincome ********;
_pctile hhincome, p(20,40,60,80);
scalar r1=r(r1);
scalar r2=r(r2);
scalar r3=r(r3);
scalar r4=r(r4);

gen hhincome1=0;
replace hhincome1=1 if hhincome<scalar(r1);

gen hhincome2=0;
replace hhincome2=1 if hhincome>=scalar(r1) & hhincome<scalar(r2);

gen hhincome3=0;
replace hhincome3=1 if hhincome>=scalar(r2) & hhincome<scalar(r3);

gen hhincome4=0;
replace hhincome4=1 if hhincome>=scalar(r3)  & hhincome<scalar(r4);

gen hhincome5=0;
replace hhincome5=1 if hhincome>scalar(r4);

gen inc_inst=0;
replace inc_inst=1 if hhincome1==1;
replace inc_inst=2 if hhincome2==1;
replace inc_inst=3 if hhincome3==1;
replace inc_inst=4 if hhincome4==1;

*********** Dummies for income II ************;
replace hhincome=hhincome*10000;

gen hh1=0;
replace hh1=1 if hhincome<=15000;
gen hh2=0;
replace hh2=1 if hhincome>15000 & hhincome<=25000;
gen hh3=0;
replace hh3=1 if hhincome>25000 & hhincome<=35000;
gen hh4=0;
replace hh4=1 if hhincome>35000 & hhincome<=45000;
gen hh5=0;
replace hh5=1 if hhincome>45000 & hhincome<=57000;
gen hh6=0;
replace hh6=1 if hhincome>57000;

*/;
gen hh_inst=0;
replace hh_inst=1 if hh1==1;
replace hh_inst=2 if hh2==1;
replace hh_inst=3 if hh3==1;
replace hh_inst=4 if hh4==1;
replace hh_inst=5 if hh5==1;
replace hh_inst=6 if hh6==1;
*replace hh_inst=7 if hh7==1;
*replace hh_inst=8 if hh8==1;
*replace hh_inst=9 if hh9==1;



replace hhincome=hhincome/10000;



*********** Dummies for nwealth ************;

replace nwealth=nwealth/acpi*100;
gen lnwealth=.;
replace lnwealth=log(1+abs(nwealth)) if nwealth>=0;
replace lnwealth=-log(1+abs(nwealth)) if nwealth<0;

gen nw1=0;
replace nw1=1 if nwealth<=10000;
gen nw2=0;
replace nw2=1 if nwealth>10000 & nwealth<=80000;
gen nw3=0;
replace nw3=1 if nwealth>80000 & nwealth<=200000;
gen nw4=0;
replace nw4=1 if nwealth>200000 & nwealth<=500000;
gen nw5=0;
replace nw5=1 if nwealth>500000;


***** Generate alternative wealth variables *****;
gen housewealth= nwealth;
replace housewealth=housewealth-vmresid/acpi*100+vdebtmresid/acpi*100 if debtmresid==1;

replace housewealth=housewealth + vdebtprop1/acpi*100 - p2_39_1*(p2_37_1/100)/acpi*100 if vdebtprop1>0;
replace housewealth=housewealth + vdebtprop2/acpi*100 - p2_39_2*(p2_37_1/100)/acpi*100 if vdebtprop2>0;
replace housewealth=housewealth + vdebtprop3/acpi*100 - p2_39_3*(p2_37_1/100)/acpi*100 if vdebtprop3>0;
replace housewealth=housewealth + vdebtprop4/acpi*100 - p2_39_4*(p2_37_1/100)/acpi*100 if vdebtprop4>0;

gen lhousingw=.;
replace lhousingw=log(1+abs(housewealth)) if housewealth>=0;
replace lhousingw=-log(1+abs(housewealth)) if housewealth<0;

gen buswealth=nwealth;
replace buswealth=buswealth-valhog/acpi*100+vbusloan;

gen lbusloanw=.;
replace lbusloanw=log(1+abs(buswealth)) if buswealth>=0;
replace lbusloanw=-log(1+abs(buswealth)) if buswealth<0;

gen cardwealth=nwealth;
replace cardwealth=cardwealth+vcredcard;

gen lcredcardw=.;
replace lcredcardw=log(1+abs(cardwealth)) if cardwealth>=0;
replace lcredcardw=-log(1+abs(cardwealth)) if cardwealth<0;

gen otherwealth=nwealth;
replace otherwealth=otherwealth-vrestbis;

gen lrestbisw=.;
replace lrestbisw=log(1+abs(otherwealth)) if otherwealth>=0;
replace lrestbisw=-log(1+abs(otherwealth)) if otherwealth<0;
*********** Dummies for housing wealth ************;

gen housingw1=0;
replace housingw1=1 if housewealth<=10000;
gen housingw2=0;
replace housingw2=1 if housewealth>10000 & housewealth<=80000;
gen housingw3=0;
replace housingw3=1 if housewealth>80000 & housewealth<=200000;
gen housingw4=0;
replace housingw4=1 if housewealth>200000 & housewealth<=500000;
gen housingw5=0;
replace housingw5=1 if housewealth>500000;

*********** Dummies for business wealth ************;

gen busloanw1=0;
replace busloanw1=1 if buswealth<=10000;
gen busloanw2=0;
replace busloanw2=1 if buswealth>10000 & buswealth<=80000;
gen busloanw3=0;
replace busloanw3=1 if buswealth>80000 & buswealth<=200000;
gen busloanw4=0;
replace busloanw4=1 if buswealth>200000 & buswealth<=500000;
gen busloanw5=0;
replace busloanw5=1 if buswealth>500000;

*********** Dummies for credit card wealth ************;

gen credcardw1=0;
replace credcardw1=1 if cardwealth<=10000;
gen credcardw2=0;
replace credcardw2=1 if cardwealth>10000 & cardwealth<=80000;
gen credcardw3=0;
replace credcardw3=1 if cardwealth>80000 & cardwealth<=200000;
gen credcardw4=0;
replace credcardw4=1 if cardwealth>200000 & cardwealth<=500000;
gen credcardw5=0;
replace credcardw5=1 if cardwealth>500000;


*********** Dummies for other debts wealth ************;

gen restbisw1=0;
replace restbisw1=1 if otherwealth<=10000;
gen restbisw2=0;
replace restbisw2=1 if otherwealth>10000 & otherwealth<=80000;
gen restbisw3=0;
replace restbisw3=1 if otherwealth>80000 & otherwealth<=200000;
gen restbisw4=0;
replace restbisw4=1 if otherwealth>200000 & otherwealth<=500000;
gen restbisw5=0;
replace restbisw5=1 if otherwealth>500000;

foreach f of var * { ;
	rename `f' `f'_imp`x' ;
} ;
rename h_2005_imp`x' h2005;
drop p6*;
save wave2005_imp`x'.dta, replace;

};


cd "H:\Mi unidad\Grant_new\EFF";
use "H:\Mi unidad\Grant_new\EFF\Imputation1\wave2005_imp1.dta";
joinby h2005 using "H:\Mi unidad\Grant_new\EFF\Imputation2\wave2005_imp2";
joinby h2005 using "H:\Mi unidad\Grant_new\EFF\Imputation3\wave2005_imp3";
joinby h2005 using "H:\Mi unidad\Grant_new\EFF\Imputation4\wave2005_imp4";
joinby h2005 using "H:\Mi unidad\Grant_new\EFF\Imputation5\wave2005_imp5";



save "H:\Mi unidad\Grant_new\wave2005.dta", replace;


erase  "H:\Mi unidad\Grant_new\EFF\Imputation1\wave2005_imp1.dta";
erase "H:\Mi unidad\Grant_new\EFF\Imputation2\wave2005_imp2.dta";
erase "H:\Mi unidad\Grant_new\EFF\Imputation3\wave2005_imp3.dta";
erase "H:\Mi unidad\Grant_new\EFF\Imputation4\wave2005_imp4.dta";
erase "H:\Mi unidad\Grant_new\EFF\Imputation5\wave2005_imp5.dta";

*****************************************************************;
************************* 2008 **********************************;
*****************************************************************;

foreach x in 1 2 3 4 5{; 


cd "H:\Mi unidad\Grant_new\EFF\Imputation`x'";


use seccion6_2008_imp`x'.dta, clear;

joinby h_2008 using otras_secciones_2008_imp`x'.dta;

gen year=2008;


********************************************************************;
** Annual and monthly consumer price index to be used (base 2010) **;
********************************************************************;

gen acpi=81.06;
replace acpi=88.96 if year==2005;
replace acpi=98.52 if year==2008;
replace acpi=103.20 if year==2011;
replace acpi=107.05 if year==2014;

gen mcpi=82.73 					 /* mean oct02-may03 */;
replace mcpi=91.14 if year==2005 /* mean nov05-may06 */;
replace mcpi=98.10 if year==2008 /* mean nov08-jun09 */;
replace mcpi=104.33 if year==2011 /* mean oct11-apr12 */;
replace mcpi=106.42 if year==2014 /* mean sept14-mar15*/;


*NET WEALTH AND INCOME;

*1.- FOR THE PERCENTAGE OF HOUSEHOLDS OWNING THAT ASSET;

*REAL ASSETS;

*MAIN RESIDENCE;
*To calculate the percentage of households that own their main residence we use the variable p2_1;

gen np2_1=(p2_1==2 & p2_5>0 & p2_5~=.);

gen owner=0;
replace owner=1 if np2_1==1;

gen renter=0 /*renter or (only 2014) renter with purchase option*/;
replace renter=1 if p2_1==1;

gen freeuse=0;
replace freeuse=1 if p2_1==3;

*OTHER REAL ESTATE PROPERTIES;
*To calculate the percentage of households that own other real estate properties we use the variable np2_32; 
gen np2_32=((p2_32==1 & p2_33>=1 & p2_33~=. & p2_39_1>0 & p2_39_1~=.)|
            (p2_32==1 & p2_33>=2 & p2_33~=. & p2_39_2>0 & p2_39_2~=.)|
            (p2_32==1 & p2_33>=3 & p2_33~=. & p2_39_3>0 & p2_39_3~=.)|
            (p2_32==1 & p2_33>3  & p2_33~=. & p2_39_4>0 & p2_39_4~=.));

gen othowner=.;
replace othowner=1 if np2_32==1;
replace othowner=0 if np2_32==0;

*JEWELLERY, WORKS OF ART, ANTIQUES;
*To calculate the percentage of households that own jewellery, works of art and antiques we use the variable np2_82;
gen np2_82=(p2_82==1 & p2_84>0 & p2_84~=.);

gen jewel=.;
replace jewel=0 if np2_82==0;
replace jewel=1 if np2_82==1;


*VALOR DEL NEGOCIO POR TRABAJOS POR CUENTA PROPIA;
*VALUE OF BUSINESSES RELATED TO SELF-EMPLOYMENT;
gen haveneg =(p4_101==1);

gen valhog =0;
replace valhog =valhog + p4_111_1 if p4_101==1 & p4_111_1>0 & p4_111_1~=.;
replace valhog =valhog + p4_111_2 if p4_101==1 & p4_111_2>0 & p4_111_2~=.;
replace valhog =valhog + p4_111_3 if p4_101==1 & p4_111_3>0 & p4_111_3~=.;
replace valhog =valhog + p4_111_4 if p4_101==1 & p4_111_4>0 & p4_111_4~=.;
replace valhog =valhog + p4_111_5 if p4_101==1 & p4_111_5>0 & p4_111_5~=.;
replace valhog =valhog + p4_111_6 if p4_101==1 & p4_111_6>0 & p4_111_6~=.;

gen havenegval =(haveneg==1 & valhog>0);


*ALGUN TIPO DE ACTIVO REAL;
*SOME KIND OF REAL ASSET;

gen  tienereal=(np2_1==1|np2_32==1|np2_82==1| havenegval==1);


*ACTIVOS FINANCIEROS;
*FINANCIAL ASSETS;


*ACCOUNTS AND DEPOSITS USABLE FOR PAYMENTS;
*To calculate the percentage of households that own accounts and deposits usable for payments and that declare a strictly positive value 
*for the balance of those accounts we generate a new variable;

gen np4_5=(p4_5==1 & p4_7_3>0 & p4_7_3~=.);
rename np4_5 account_pay;
label var account_pay "households that own accounts and deposits usable for payments and that declare a strictly positive value";

*LISTED SHARES;
*To calculate the percentage of households that own listed and that declare a strictly positive value for that portfolio we generate a new variable;

gen np4_10=(p4_10==1 & p4_15>0 & p4_15~=.);

rename np4_10 listshare;
label var listshare "household that own listed shares";


*UNLISTED SHARES AND OTHER EQUITY;
*To calculate the percentage of households that own unlisted shares and other equity and that declare a strictly positive
* value for that portfolio we generate a new variable;

gen np4_18=(p4_18==1 & p4_24>0 & p4_24~=.);
rename np4_18 unlistshare;
label var unlistshare "household that own unlisted shares and other equity";


*FIXED-INCOME SECURITIES;
*To calculate the percentage of households that own fixed-income securities and that declare a strictly positive value for that portfolio we generate a new variable;

gen np4_33=(p4_33==1 & p4_35>0 & p4_35~=.);

rename np4_33 fixsec;
label var fixsec "household that own fixed-income securities ";

*MUTUAL FUNDS (FFII);
*To calculate the percentage of households that own mutual funds and that declare a strictly positive value for that portfolio we generate a new variable;

gen np4_27=((p4_27==1 & p4_28>=1 & p4_28~=. & p4_31_1>0 & p4_31_1~=.)|
            (p4_27==1 & p4_28>=2 & p4_28~=. & p4_31_2>0 & p4_31_2~=.)|
            (p4_27==1 & p4_28>=3 & p4_28~=. & p4_31_3>0 & p4_31_3~=.)|
            (p4_27==1 & p4_28>=4 & p4_28~=. & p4_31_4>0 & p4_31_4~=.)|
            (p4_27==1 & p4_28>=5 & p4_28~=. & p4_31_5>0 & p4_31_5~=.)|
            (p4_27==1 & p4_28>=6 & p4_28~=. & p4_31_6>0 & p4_31_6~=.)|
            (p4_27==1 & p4_28>=7 & p4_28~=. & p4_31_7>0 & p4_31_7~=.)|
            (p4_27==1 & p4_28>=8 & p4_28~=. & p4_31_8>0 & p4_31_8~=.)|
            (p4_27==1 & p4_28>=9 & p4_28~=. & p4_31_9>0 & p4_31_9~=.)|
            (p4_27==1 & p4_28>9 & p4_28~=. & p4_31_10>0 & p4_31_10~=.));

rename np4_27 mutfunds;
label var mutfunds "household that own mutual funds";

*CUENTAS VIVIENDA Y CUENTAS NO UTILIZABLES PARA REALIZAR PAGOS;
*Para calcular la proporción de hogares que poseen cuentas y depósitos no utilizables para realizar pagos generamos una nueva variable cuentas;

*HOUSE-PURCHASE SAVINGS ACCOUNTS AND ACCOUNTS NOT USABLE FOR PAYMENTS;
*To calculate the percentage of households that own house-purchase saving accounts and/or accounts not usable for payments and 
*that declare a strictly positive value for the balance of those accounts we generate a new variable;

gen cuentas=((p4_3==1 & p4_7_1>0 & p4_7_1~=.)|(p4_4==1 & p4_7_2>0 & p4_7_2~=.));

rename cuentas account_nopay;
label var account_nopay "household that own accounts and deposits not usable for payments";


*PENSION SCHEMES (plan pensiones);
*To calculate the percentage of households that own pension schemes and that declare a strictly positive value for the balance of those pension schemes we generate a new variable;

gen np5_1=((p5_1==1 & p5_1a>=1 & p5_1a~=. & p5_7_1>0 & p5_7_1~=.)|
           (p5_1==1 & p5_1a>=2 & p5_1a~=. & p5_7_2>0 & p5_7_2~=.)|
           (p5_1==1 & p5_1a>=3 & p5_1a~=. & p5_7_3>0 & p5_7_3~=.)|
           (p5_1==1 & p5_1a>=4 & p5_1a~=. & p5_7_4>0 & p5_7_4~=.)|
           (p5_1==1 & p5_1a>=5 & p5_1a~=. & p5_7_5>0 & p5_7_5~=.)|
           (p5_1==1 & p5_1a>=6 & p5_1a~=. & p5_7_6>0 & p5_7_6~=.)|
           (p5_1==1 & p5_1a>=7 & p5_1a~=. & p5_7_7>0 & p5_7_7~=.)|
           (p5_1==1 & p5_1a>=8 & p5_1a~=. & p5_7_8>0 & p5_7_8~=.)|
           (p5_1==1 & p5_1a>=9 & p5_1a~=. & p5_7_9>0 & p5_7_9~=.)|
           (p5_1==1 & p5_1a>9 & p5_1a~=. & p5_7_10>0 & p5_7_10~=.));

rename np5_1 penplan;
label var penplan "household that own pension schemes";
*SEGUROS DE VIDA;
*Para calcular la proporción de hogares que tienen seguros tipo unit linked o mixto generamos una nueva variable;

*To calculate the percentage of households that own unit-linked or mixed life insurance we generate a new variable;

gen seguro=((p5_9==1 & p5_11a>=1 & p5_11a~=. & p5_13_1==2 & p5_14_1>0 & p5_14_1~=.)|(p5_9==1 & p5_11a>=2 & p5_11a~=.
 & p5_13_2==2 & p5_14_2>0 & p5_14_2~=.)|(p5_9==1 & p5_11a>=3 & p5_11a~=. & p5_13_3==2 & p5_14_3>0 & p5_14_3~=.)|
 (p5_9==1 & p5_11a>=4 & p5_11a~=. & p5_13_4==2 & p5_14_4>0 & p5_14_4~=.)|(p5_9==1 & p5_11a>=5 & p5_11a~=. & p5_13_5==2 & p5_14_5>0 & p5_14_5~=.)|
 (p5_9==1 & p5_11a==6 & p5_11a~=. & p5_13_6==2 & p5_14_6>0 & p5_14_6~=.)|(p5_9==1 & p5_11a>=1 & p5_11a~=. & p5_13_1==3 & p5_14_1>0 & p5_14_1~=.)|
 (p5_9==1 & p5_11a>=2 & p5_11a~=. & p5_13_2==3 & p5_14_2>0 & p5_14_2~=.)|(p5_9==1 & p5_11a>=3 & p5_11a~=. & p5_13_3==3 & p5_14_3>0 & p5_14_3~=.)|
 (p5_9==1 & p5_11a>=4 & p5_11a~=. & p5_13_4==3 & p5_14_4>0 & p5_14_4~=.)|(p5_9==1 & p5_11a>=5 & p5_11a~=. & p5_13_5==3 & p5_14_5>0 & p5_14_5~=.)|
 (p5_9==1 & p5_11a>5 & p5_11a~=. & p5_13_6==3 & p5_14_6>0 & p5_14_6~=.));	

rename seguro lifeinsur;
label var lifeinsur "household that own unit-linked or mixed life insurance";

*PLANES DE PENSIONES INCLUYENDO SEGUROS DE VIDA DE INVERSION O MIXTOS;
*PENSION SCHEMES INCLUDING UNIT-LINKED OR MIXED LIFE INSURANCE;

gen penseg=(penplan==1|lifeinsur==1);

*PORTFOLIOS UNDER MANAGEMENT (carteras gestionadas);

gen cart_gest=((p4_41==1 & p4_42==1) & p4_43>0 & p4_43~=.);


*OTHER FINANCIAL ASSETS; 

*To calculate the percentage of households to whom the business or other people owe money we generate the variable sideuda; 


*PROGRAMA PARA CALCULAR LO QUE LES DEBEN LOS NEGOCIOS A LOS DISTINTOS MIEMBROS DEL HOGAR (P4_116);
*PROGRAM TO OBTAIN WHAT THE BUSINESSES OWE TO THE DIFFERENT HOUSEHOLD MEMBERS (P4_116);

gen valdeuhog=0;
gen havedeuhog=0;
forvalues m=1/6   {;
	replace valdeuhog=valdeuhog+p4_116_`m' if (p4_116_`m'>0 & p4_116_`m'~=.);
	replace havedeuhog=1 if (p4_115_`m'==1);
	};
gen sideuda=((havedeuhog ==1 & valdeuhog>0)|(p4_37==1 & p4_38>0 & p4_38~=.));

rename sideuda creditor;
label var creditor "household to whom the business or other people owe money";

*ALGUN TIPO DE ACTIVO FINANCIERO;
*SOME TYPE OF FINANCIAL ASSET;

gen tienefin=(account_pay==1|listshare==1|unlistshare==1|fixsec==1|mutfunds==1|account_nopay==1|penplan==1|lifeinsur==1|creditor==1|cart_gest==1);

*ALGUN TIPO DE ACTIVO;
*SOME TYPE OF ASSET;

gen tiene=(tienereal==1|tienefin==1);
rename tiene anyasset;




*2.- PARA EL VALOR DE DICHOS ACTIVOS;
*2.- FOR THE VALUE OF THOSE ASSETS;

*ACTIVOS REALES;
*REAL ASSETS;

*MAIN RESIDENCE;
*To obtain the value of the main residence we use the variable p2_5;
gen np2_5=p2_5 if p2_1b==1;
replace np2_5=p2_5*(p2_1c/100) if p2_1b==2;

rename np2_5 vmresid;
label var vmresid "value of the main residence";

*OTHER REAL ESTATE PROPERTIES;
*To obtain the value of the other real estate properties we generate a new variable;

gen otraspr=0;
replace otraspr=otraspr+p2_39_1*(p2_37_1/100) if (p2_33>=1 & p2_33~=. & p2_39_1>=0 & p2_39_1~=. & p2_37_1>0 & p2_37_1~=.);
replace otraspr=otraspr+p2_39_2 *(p2_37_2/100) if (p2_33>=2 & p2_33~=. & p2_39_2>=0 & p2_39_2~=. & p2_37_2>0 & p2_37_2~=.);
replace otraspr=otraspr+p2_39_3* (p2_37_3/100) if (p2_33>=3 & p2_33~=. & p2_39_3>=0 & p2_39_3~=. & p2_37_3>0 & p2_37_3~=.);
replace otraspr=otraspr+p2_39_4 if (p2_33>3 & p2_33~=. & p2_39_4>=0 & p2_39_4~=.);

rename otraspr vothprop;
label var vothprop "value of the other real estate properties";


*JEWELLERY, WORKS OF ART, ANTIQUES;
*To obtain the value of the jewellery, works of art and antiques we use the variable p2_84;
rename p2_84 vjewel;
label var vjewel "value of the jewellery, works of art and antiques";

*VALOR DEL NEGOCIO POR TRABAJOS POR CUENTA PROPIA;
*la mediana del valor del negocio será la mediana de valhog if havenegval==1; 

*TBD;

*VALUE OF THE BUSINESS RELATED TO SELF-EMPLOYMENT;
*The median of the business value is equal to the median of valhog if havenegval==1;


*ACTIVOS FINANCIEROS;
*FINANCIAL ASSETS;

*CUENTAS Y DEPOSITOS UTILIZABLES PARA REALIZAR PAGOS;
*Para calcular el saldo de las cuentas y depósitos para realizar pagos utilizamos la variable p4_7_3;


*ACCOUNTS AND DEPOSITS USABLE FOR PAYMENTS;
*To obtain the balance of the accounts and deposits usable for payments we use the variable p4_7_3;
rename p4_7_3 vaccount_pay;



*ACCIONES COTIZADAS EN BOLSA;
*Para calcular el valor de las acciones cotizadas utilizamos la variable p4_15;


*LISTED SHARES;
*To obtain the value of the listed shares we use the variable p4_15;
rename p4_15 vlistshare;

*ACCIONES NO COTIZADAS EN BOLSA Y PARTICIPACIONES;
*Para calcular el valor de las acciones no cotizadas y participaciones utilizamos la variable p4_24;

*UNLISTED SHARES ANDOTHER EQUITY;
*To obtain the value of the unlisted shares and other equity we use the variable p4_24;
rename p4_24 vunlist;

*VALORES DE RENTA FIJA;
*Para calcular el valor de los valores de renta fija utilizamos la variable p4_35;

*FIXED-INCOME SECURITIES;
*To obtain the value of the fixed-income securities we use the variable p4_35;

rename p4_35 vfixsec;

*FONDOS DE INVERSION;
*Para calcular el valor total de los fondos de inversión utilizamos la variable allf calculada como (i) la suma de los valores de cada uno de los fondos 
*de inversión que posee el hogar (p4_31_i, i=1,…,10) si el número de estos fondos es menor o igual a 10, y (ii) el valor total de los fondos de inversión 
*del hogar si posee más de 10 fondos (p4_28a);

*MUTUAL FUNDS;
*To obtain the total value of mutual funds we use the variable allf calculated as (i) the addition of the values of each mutual fund that the household
* owns (p4_31_i, i=1,…,10) if the number of these funds is 10 or less, and (ii) the household mutual funds’ total value if this one owns more than 10 (p4_28a);

egen allf=rowtotal(p4_31*);
replace allf=p4_28a if p4_28>10;
label var allf "Total value of mutual funds";


*CUENTAS VIVIENDA Y CUENTAS NO UTILIZABLES PARA REALIZAR PAGOS;
*Para calcular el saldo de las cuentas y depósitos no utilizables para realizar pagos generamos una nueva variable;

*HOME-PURCHASE SAVINGS ACCOUNTS AND ACCOUNTS NOT USABLE FOR PAYMENTS;
*To obtain the balance of the accounts and deposits not usable for payments we generate a new variable;  

gen salcuentas=0;
replace salcuentas = salcuentas +p4_7_1 if p4_3==1;
replace salcuentas = salcuentas + p4_7_2 if p4_4==1;

rename salcuentas vaccount_nopay;
label var vaccount_nopay "balance of the accounts and deposits not usable for payments";

*PLANES DE PENSIONES;
*Para calcular valor actualizado de los planes de pensiones generamos una nueva variable;

*PENSION SCHEMES;
*To obtain the current value of the pension schemes we generate a new variable;

gen valor=0; 
replace valor = valor +p5_7_1 if (p5_1==1 & p5_7_1>=0 & p5_7_1~=. );
replace valor = valor + p5_7_2 if (p5_1==1 & p5_7_2>=0 & p5_7_2~=.);
replace valor = valor + p5_7_3 if (p5_1==1 & p5_7_3>=0 & p5_7_3~=.);
replace valor = valor + p5_7_4 if (p5_1==1 & p5_7_4>=0 & p5_7_4~=.);
replace valor = valor + p5_7_5 if (p5_1==1 & p5_7_5>=0 & p5_7_5~=.);
replace valor = valor + p5_7_6 if (p5_1==1 & p5_7_6>=0 & p5_7_6~=.);
replace valor = valor + p5_7_7 if (p5_1==1 & p5_7_7>=0 & p5_7_7~=.);
replace valor = valor + p5_7_8 if (p5_1==1 & p5_7_8>=0 & p5_7_8~=.);
replace valor = valor + p5_7_9 if (p5_1==1 & p5_7_9>=0 & p5_7_9~=.);
replace valor = valor + p5_7_10 if (p5_1==1 & p5_7_10>=0 & p5_7_10~=.);


rename valor vpenplan;
label var vpenplan "current value of the pension schemes";

*No consideramos las mutualidades;
*We do not consider mutual insurance;

*SEGUROS DE VIDA;
*Para calcular el valor de estos seguros tipo unit linked o mixto generamos una nueva variable;

*LIFE INSURANCE;
*To obtain the value of the unit-linked or mixed life insurance we generate a new variable;


gen valseg=0;
replace valseg = valseg +p5_14_1 if ((p5_13_1==2| p5_13_1==3) & p5_14_1>=0 & p5_14_1~=.);
replace valseg = valseg +p5_14_2 if ((p5_13_2==2| p5_13_2==3) & p5_14_2>=0 & p5_14_2~=.);
replace valseg = valseg +p5_14_3 if ((p5_13_3==2| p5_13_3==3) & p5_14_3>=0 & p5_14_3~=.);
replace valseg = valseg +p5_14_4 if ((p5_13_4==2| p5_13_4==3) & p5_14_4>=0 & p5_14_4~=.);
replace valseg = valseg +p5_14_5 if ((p5_13_5==2| p5_13_5==3) & p5_14_5>=0 & p5_14_5~=.);
replace valseg = valseg +p5_14_6 if ((p5_13_6==2| p5_13_6==3) & p5_14_6>=0 & p5_14_6~=.);


rename valseg vlifeinsur;
label var vlifeinsur "value of the unit-linked or mixed life insurance";

*PLANES DE PENSIONES INCLUYENDO SEGUROS DE VIDA DE INVERSION O MIXTOS;
*PENSION SCHEMES INCLUDING UNIT-LINKED OR MIXED LIFE INSURANCE;

gen valpenseg=vpenplan+vlifeinsur;
rename valpenseg vpeninsur;
label var vpeninsur "value of pension schemes plus unit-linked or mixed life insurance";

*OTROS ACTIVOS FINANCIEROS;
*Para calcular el valor de la mediana de lo que se debe al hogar, utilizamos las variables valdeuhog y p4_38 y generamos una nueva variable;

*OTHER FINANCIAL ASSETS;
*To obtain the median of how much is owed to the household, we use the variables valdeuhog and p4_38 and generate a new variable; 

gen odeuhog=0;

replace odeuhog = odeuhog +valdeuhog if (valdeuhog>0);
replace odeuhog = odeuhog +p4_38 if (p4_38>0 & p4_38~=.);

rename odeuhog vcreditor;
label var vcreditor "how much is owed to the household";

*CUADRO 7: PROPORCION DE HOGARES Y MEDIANA DEL VALOR DE LOS DISTINTOS TIPOS DE DEUDA PENDIENTES;
*TABLE 7: PERCENTAGE OF HOUSEHOLDS AND VALUE’S MEDIAN OF THE DIFFERENT TYPES OF OUTSTANDING DEBT;

*DEUDAS  CLASIFICADAS POR TIPO DE ACTIVO INMOBILIARIO (TODO TIPO DE PRESTAMOS);
*DEBT CLASSIFIED BY TYPE OF REAL ESTATE ASSET (ALL KIND OF LOANS);

*VIVIENDA PRINCIPAL;
*MAIN RESIDENCE;

*Para calcular la proporción de hogares que tienen deudas pendientes de préstamos solicitados para la adquisición de la vivienda principal, utilizamos p2_8;
*To obtain the percentage of households that have outstanding debt from loans used to purchase their main residence, we generate a new variable;

gen np2_8=p2_8;
replace np2_8=0 if p2_8==.;

rename np2_8 debtmresid;
label var debtmresid "have outstanding debt from loans used to purchase main residence";

*Para calcular el valor de las deudas pendientes de préstamos solicitados para la adquisición de la vivienda principal, generamos una nueva variable;
*To obtain the value of the outstanding debts from loans used to purchase their main residence, we generate a new variable;

gen dvivpral=0;

replace dvivpral= dvivpral +p2_12_1 if  (p2_8a>=1 & p2_8a~=. & p2_12_1>0 & p2_12_1~=.);

replace dvivpral= dvivpral + p2_12_2 if (p2_8a>=2 & p2_8a~=. &  p2_12_2>0 & p2_12_2~=.);

replace dvivpral= dvivpral +p2_12_3  if (p2_8a>=3 & p2_8a~=. & p2_12_3>0 & p2_12_3~=.);

replace dvivpral= dvivpral +p2_12_4  if (p2_8a>3 & p2_8a~=. & p2_12_4>0 & p2_12_4~=.);

rename dvivpral vdebtmresid;
label var vdebtmresid "value of outstanding debts from loans used to purchase main residence";

*OTRAS PROPIEDADES INMOBILIARIAS DIFERENTES DE LA VIVIENDA PRINCIPAL;
*OTHER REAL ESTATE PROPERTIES DIFFERENT FROM THE MAIN RESIDENCE;

*Para calcular la proporción de hogares que tienen deudas pendientes de préstamos solicitados para la adquisición de otras propiedades inmobiliarias diferentes de la vivienda principal, generamos una nueva variable;

*To obtain the percentage of households that have outstanding debts from loans used to purchase other real estate properties different from the main 
*residence, we generate a new variable;

gen dpdte=(p2_50_1==1|p2_50_2==1|p2_50_3==1|p2_50_4==1);
rename dpdte debtothprop;
label var debtothprop "have outstanding debts from loans used to purchase other real estate properties";

*Para calcular el valor de las deudas pendientes de préstamos solicitados para la adquisición de otras propiedades inmobiliarias diferentes de la vivienda principal, generamos cuatro nuevas variables;

*To obtain the value of the outstanding debts from loans used to purchase other real estate properties different from the main residence, we generate
* four new variables;

*PARA LA PRIMERA PROPIEDAD INMOBILIARIA;
*FOR THE FIRST REAL ESTATE PROPERTY;

gen dprop1=0;

replace dprop1= dprop1+p2_55_1_1 if (p2_51_1>=1 & p2_51_1~=.  &  p2_55_1_1>0 & p2_55_1_1~=.);

replace dprop1= dprop1+ p2_55_1_2 if (p2_51_1>=2 & p2_51_1~=.  & p2_55_1_2>0 & p2_55_1_2~=.);

replace dprop1= dprop1+p2_55_1_3  if (p2_51_1>=3 & p2_51_1~=.  & p2_55_1_3>0 & p2_55_1_3~=.);


*PARA LA SEGUNDA PROPIEDAD INMOBILIARIA;
*FOR THE SECOND REAL ESTATE PROPERTY;

gen dprop2=0;

replace dprop2= dprop2+p2_55_2_1 if (p2_51_2>=1 & p2_51_2~=. & p2_55_2_1>0 & p2_55_2_1~=.);

replace dprop2= dprop2+ p2_55_2_2 if (p2_51_2>=2 & p2_51_2~=. & p2_55_2_2>0 & p2_55_2_2~=.);

replace dprop2= dprop2+ p2_55_2_3  if (p2_51_2>=3 & p2_51_2~=. & p2_55_2_3>0 & p2_55_2_3~=.);


*PARA LA TERCERA PROPIEDAD INMOBILIARIA;
*FOR THE THIRD REAL ESTATE PROPERTY;

gen dprop3=0;

replace dprop3= dprop3+p2_55_3_1 if (p2_51_3>=1 & p2_51_3~=. & p2_55_3_1>0 & p2_55_3_1~=.);

replace dprop3= dprop3+ p2_55_3_2 if (p2_51_3>=2 & p2_51_3~=. & p2_55_3_2>0 & p2_55_3_2~=.);

replace dprop3= dprop3+ p2_55_3_3  if (p2_51_3>=3 & p2_51_3~=. & p2_55_3_3>0 & p2_55_3_3~=.);


*PARA EL RESTO DE PROPIEDADES INMOBILIARIAS CUANDO HAY MAS DE TRES;
*FOR THE REST OF REAL ESTATE PROPERTIES WHEN THESE ARE MORE THAN THREE;

gen dprop4=0;

replace dprop4= dprop4+p2_55_4 if (p2_55_4>0 & p2_55_4~=.);

forvalues i=1(1)4{;
rename dprop`i' vdebtprop`i';
};

label var vdebtprop1 "value of the outstanding debts from loans used to purchase other real estate property #1";
label var vdebtprop2 "value of the outstanding debts from loans used to purchase other real estate property #2";
label var vdebtprop3 "value of the outstanding debts from loans used to purchase other real estate property #3";
label var vdebtprop4 "value of the outstanding debts from loans used to purchase other real estate properties #4";


*CONSIDERANDO CONJUNTAMENTE TODAS LAS PROPIEDADES INMOBILIARIAS DIFERENTES DE LA VIVIENDA PRINCIPAL;
*CONSIDERING ALL REAL ESTATE PROPERTIES DIFFERENT FROM THE MAIN RESIDENCE;

gen deuoprop= vdebtprop1+ vdebtprop2+ vdebtprop3+ vdebtprop4 ; 
rename deuoprop vdebtothprop;
label var vdebtothprop "value of the outstanding debts from loans used to purchase other real estate properties";

*DEUDAS PENDIENTES DE PRESTAMOS SOLICITADOS PARA LA ADQUISICION DE LA VIVIENDA PRINCIPAL CON GARANTIA HIPOTECARIA;
*OUTSTANDING DEBTS FROM LOANS WITH MORTGAGE GUARANTEE USED FOR THE PURCHASE OF THE MAIN RESIDENCE;

*Para calcular la proporción de hogares que tienen deudas pendientes de préstamos CON garantía hipotecaria solicitados para la adquisición de la vivienda principal, generamos una nueva variable;
*To obtain the percentage of households that have outstanding debts from loans with mortgage guarantee used for the purchase of the main residence, 
* we generate a new variable;

gen dpdtehipo = (p2_9_1==1|p2_9_2==1|p2_9_3==1|p2_9_4==1);
rename dpdtehipo mortgmresid;
label var mortgmresid " have mortgage for the purchase of the main residence";

*Para calcular el valor de las deudas pendientes de préstamos CON garantía hipotecaria solicitados para la adquisición de la vivienda principal, generamos una nueva variable;
*To obtain the value of the outstanding debts from loans with mortgage guarantee used for the purchase of the main residence, we generate a new variable;

gen deuhipv =0;

replace deuhipv= deuhipv + p2_12_1 if (p2_8a>=1 & p2_8a~=. & p2_9_1==1 & p2_12_1>0 & p2_12_1~=.);

replace deuhipv = deuhipv + p2_12_2 if (p2_8a>=2 & p2_8a~=. & p2_9_2==1 &  p2_12_2>0 & p2_12_2~=.);

replace deuhipv= deuhipv +p2_12_3  if (p2_8a>=3 & p2_8a~=. & p2_9_3==1 &  p2_12_3>0 & p2_12_3~=.);

replace deuhipv= deuhipv +p2_12_4  if (p2_8a>3 & p2_8a~=. & p2_8a~=. & p2_9_4==1 &  p2_12_4>0 & p2_12_4~=.);

rename deuhipv vmortgmresid;
label var vmortgmresid "value of outstanding mortgages for the purchase of the main residence";


*OTRAS DEUDAS PENDIENTES NO ASOCIADAS A LA ADQUISICION DE ACTIVOS INMOBILIARIOS;
*OTHER OUTSTANDING DEBT NOT RELATED TO THE PURCHASE OF REAL ESTATE ASSETS;

*DEUDAS PENDIENTES DE PRESTAMOS HIPOTECARIOS Y OTROS PRESTAMOS CON GARANTIA REAL;
*OUTSTANDING DEBTS FROM MORTGAGES AND OTHER SECURED LOANS);

*Para calcular la proporción de hogares que tienen deudas pendientes por prestamos hipotecarios y otros préstamos con garantía real generamos una nueva variable;
*To obtain the percentage of households that have outstanding debts from mortgages and other secured loans we generate a new variable;

gen hipo=(p3_2_1==1| p3_2_2==1| p3_2_3==1| p3_2_4==1|p3_2_5==1| p3_2_6==1| p3_2_7==1| p3_2_8==1|
p3_2_1==2| p3_2_2==2| p3_2_3==2| p3_2_4==2|p3_2_4==2|p3_2_5==2| p3_2_6==2| p3_2_7==2| p3_2_8==2|
p3_2_1==10| p3_2_2==10| p3_2_3==10| p3_2_4==10|p3_2_5==10| p3_2_6==10| p3_2_7==10| p3_2_8==10);


rename hipo mortgoth;
label var mortgoth "have mortgage for other porpuses";

*Para calcular el valor de las deudas pendientes por prestamos hipotecarios y otros préstamos con garantía real generamos una nueva variable;
*To obtain the value of the outstanding debts from mortgages and other loans with real guarantee we generate a new variable;

gen phipo=0;

replace phipo = phipo +p3_6_1 if ((p3_2_1==1|p3_2_1==2) & p3_6_1>0 & p3_6_1~=.);

replace phipo = phipo +p3_6_2 if ((p3_2_2==1| p3_2_2==2) & p3_6_2>0 & p3_6_2~=.);

replace phipo = phipo +p3_6_3 if ((p3_2_3==1| p3_2_3==2)  & p3_6_3>0 & p3_6_3~=.);

replace phipo = phipo +p3_6_4 if ((p3_2_4==1| p3_2_4==2) & p3_6_4>0 & p3_6_4~=.);

replace phipo = phipo +p3_6_5 if ((p3_2_5==1| p3_2_5==2) & p3_6_5>0 & p3_6_5~=.);

replace phipo = phipo +p3_6_6 if ((p3_2_6==1| p3_2_6==2) & p3_6_6>0 & p3_6_6~=.);

replace phipo = phipo +p3_6_7 if ((p3_2_7==1| p3_2_7==2) & p3_6_7>0 & p3_6_7~=.);

replace phipo = phipo +p3_6_8 if ((p3_2_8==1| p3_2_8==2) & p3_6_8>0 & p3_6_8~=.);

rename phipo vmortgoth;
label var vmortgoth "value of outstanding mortgages for other purposes";

*Variable capturing any kind of mortgage or secure debt ;
gen mortgage =0;
replace mortgage=1 if mortgoth==1 | mortgmresid==1;

*DEUDAS PENDIENTES DE PRESTAMOS PERSONALES;
*OUTSTANDING DEBTS FROM PERSONAL LOANS;

*Para calcular la proporción de hogares que tienen deudas pendientes por prestamos personales generamos una nueva variable;
*To obtain the percentage of households that have outstanding debts from personal loans we generate a new variable;

gen perso=(p3_2_1==3| p3_2_2==3| p3_2_3==3| p3_2_4==3|p3_2_5==3| p3_2_6==3| p3_2_7==3| p3_2_8==3);
rename perso personal;
label var personal "have outstanding debts from personal loans";

*Para calcular el valor de las deudas pendientes por prestamos personales generamos una nueva variable;
*To obtain the value of the outstanding debts from personal loans we generate a new variable;

gen pperso=0;

replace pperso = pperso +p3_6_1 if (p3_2_1==3 & p3_6_1>0 & p3_6_1~=.);
replace pperso = pperso +p3_6_2 if (p3_2_2==3 & p3_6_2>0 & p3_6_2~=.);
replace pperso = pperso +p3_6_3 if (p3_2_3==3 & p3_6_3>0 & p3_6_3~=.);
replace pperso = pperso +p3_6_4 if (p3_2_4==3 & p3_6_4>0 & p3_6_4~=.);
replace pperso = pperso +p3_6_5 if (p3_2_5==3 & p3_6_5>0 & p3_6_5~=.);
replace pperso = pperso +p3_6_6 if (p3_2_6==3 & p3_6_6>0 & p3_6_6~=.);
replace pperso = pperso +p3_6_7 if (p3_2_7==3 & p3_6_7>0 & p3_6_7~=.);
replace pperso = pperso +p3_6_8 if (p3_2_8==3 & p3_6_8>0 & p3_6_8~=.);

rename pperso vpersonal;
label var vpersonal "value of personal loans";


*DEUDAS PENDIENTES CON TARJETAS DE CREDITO;
*OUTSTANDING CREDIT CARD BALANCES;

*Para calcular la proporción de hogares que tienen deudas pendientes con tarjetas de credito generamos una nueva variable;
*To obtain the percentage of households that have outstanding credit card balances we generate a new variable;

gen deuda_tarj=(p8_5a>0 & p8_5a~=.);
rename deuda_tarj credcard;
label var credcard "have outstanding credit card balances";

*Para calcular el valor de las deudas pendientes con tarjetas de credito generamos una nueva variable;
*To obtain the value of outstanding credit card balances we generate a new variable;

gen ptmos_tarj=0;

replace ptmos_tarj= p8_5a if (p8_5a>0 & p8_5a~=.);
rename ptmos_tarj vcredcard;
label var vcredcard "value of outstanding credit card balances";



*OTRAS DEUDAS;
*OTHER DEBTS;

*Para calcular la proporción de hogares que tienen otras deudas pendientes generamos una nueva variable;
*To obtain the percentage of households that have other outstanding debts we generate a new variable;

gen otrasd=(p3_2_1==4| p3_2_2==4| p3_2_3==4| p3_2_4==4| p3_2_5==4| p3_2_6==4| p3_2_7==4| p3_2_8==4|p3_2_1==5| p3_2_2==5| p3_2_3==5| p3_2_4==5| p3_2_5==5|
 p3_2_6==5| p3_2_7==5| p3_2_8==5| p3_2_1==6| p3_2_2==6| p3_2_3==6| p3_2_4==6| p3_2_5==6| p3_2_6==6| p3_2_7==6| p3_2_8==6| p3_2_1==7| p3_2_2==7| p3_2_3==7|
 p3_2_4==7| p3_2_5==7| p3_2_6==7| p3_2_7==7| p3_2_8==7| p3_2_1==8| p3_2_2==8| p3_2_3==8| p3_2_4==8| p3_2_5==8| p3_2_6==8| p3_2_7==8| p3_2_8==8| p3_2_1==9|
 p3_2_2==9| p3_2_3==9| p3_2_4==9| p3_2_5==9| p3_2_6==9| p3_2_7==9| p3_2_8==9| p3_2_1==97| p3_2_2==97| p3_2_3==97| p3_2_4==97 | p3_2_5==97| p3_2_6==97| 
 p3_2_7==97| p3_2_8==97);
rename otrasd othdebt;
label var othdebt "households that have other outstanding debt";


*Para calcular el valor de las otras deudas pendientes generamos una nueva variable;
*To obtain the value of the other outstanding debts we generate a new variable;

gen potrasd =0;

replace potrasd = potrasd +p3_6_1 if ((p3_2_1==4| p3_2_1==5| p3_2_1==6| p3_2_1==7| p3_2_1==8|p3_2_1==9|
p3_2_1==97) & p3_6_1>0 & p3_6_1~=.);
replace potrasd = potrasd +p3_6_2 if ((p3_2_2==4| p3_2_2==5|  p3_2_2==6| p3_2_2==7| p3_2_2==8|p3_2_2==9|
p3_2_2==97) & p3_6_2>0 & p3_6_2~=.);
replace potrasd = potrasd +p3_6_3 if ((p3_2_3==4| p3_2_3==5| p3_2_3==6| p3_2_3==7| p3_2_3==8|p3_2_3==9|
p3_2_3==97) & p3_6_3>0 & p3_6_3~=.);
replace potrasd = potrasd +p3_6_4 if ((p3_2_4==4| p3_2_4==5| p3_2_4==6| p3_2_4==7| p3_2_4==8|p3_2_4==9|
p3_2_4==97) & p3_6_4>0 & p3_6_4~=.);
replace potrasd = potrasd +p3_6_5 if ((p3_2_5==4| p3_2_5==5| p3_2_5==6| p3_2_5==7| p3_2_5==8|p3_2_5==9|
p3_2_5==97) & p3_6_5>0 & p3_6_5~=.);
replace potrasd = potrasd +p3_6_6 if ((p3_2_6==4| p3_2_6==5| p3_2_6==6| p3_2_6==7| p3_2_6==8|p3_2_6==9|
p3_2_6==97) & p3_6_6>0 & p3_6_6~=.);
replace potrasd = potrasd +p3_6_7 if ((p3_2_7==4| p3_2_7==5| p3_2_7==6| p3_2_7==7| p3_2_7==8|p3_2_7==9|
p3_2_7==97) & p3_6_7>0 & p3_6_7~=.);
replace potrasd = potrasd +p3_6_8 if ((p3_2_8==4| p3_2_8==5| p3_2_8==6| p3_2_8==7| p3_2_8==8|p3_2_8==9|
p3_2_8==97) & p3_6_8>0 & p3_6_8~=.);

rename potrasd vothdebt;
label var vothdebt "value of the other outstanding debts";


******************************************************************************************************;
******************************************************************************************************;

*                          R A N K I N G     A: NATURE OF THE DEBT									 *;
******************************************************************************************************;
******************************************************************************************************;
gen housesec=0;
gen houseunsec=0;
gen othsecured=0;
gen consumer=0;
gen rest=0;

gen vhousesec=0;
gen vhouseunsec=0;
gen vothsecured=0;
gen vconsumer=0;
gen vrest=0;

replace vhousesec=vhousesec+p2_55_4 if p2_55_4!=. /*Consider as secured, all debts attached to fourth real state properties in advanced */;

forvalues i=1(1)4 {;
replace housesec=1 if p2_9_`i'<=2;
replace vhousesec=vhousesec+p2_12_`i' if p2_9_`i'<=2; 
replace houseunsec=1 if p2_9_`i'>2 & p2_9_`i'<=97;
replace vhouseunsec=vhouseunsec+p2_12_`i' if p2_9_`i'>2 & p2_9_`i'<=97;
};

forvalues i=1(1)3 {;
		forvalues s=1(1)3 {; 
		replace housesec=1 if p2_52_`i'_`s'<=2;
		replace vhousesec=vhousesec+p2_55_`i'_`s' if  p2_52_`i'_`s'<=2;
		replace houseunsec=1 if p2_52_`i'_`s'>2 & p2_52_`i'_`s'<=97;
		replace vhouseunsec=vhousesec+p2_55_`i'_`s' if  p2_52_`i'_`s'>2 & p2_52_`i'_`s'<=97;
};
};

forvalues i=1(1)8 {;
replace othsecured=1 if p3_2_`i'<=2;
replace vothsecured=vothsecured+p3_6_`i' if p3_2_`i'<=2;
replace consumer=1 if p3_2_`i'==3;
replace vconsumer=vconsumer+p3_6_`i' if p3_2_`i'==3;
replace rest=1 if p3_2_`i'>3 & p3_2_`i'<=97;
replace vrest=vrest+p3_6_`i' if p3_2_`i'>3 & p3_2_`i'<=97;

};


******************************************************************************************************;
******************************************************************************************************;

*                          R A N K I N G     B: OBJECIVE OF THE DEBT								 *;

******************************************************************************************************;
******************************************************************************************************;

gen housing=0;
*gen carloan=0;
gen busloan=0;
gen restbis=0;

replace housing=1 if housesec==1;
replace restbis=1 if houseunsec==1;
forvalues i=1(1)8 {;
*replace carloan=1 if p3_3_`i'==2;
replace busloan=1 if p3_3_`i'==12;
replace housing=1 if p3_3_`i'==14 & p3_2_`i'<=2;
replace restbis=1 if p3_3_`i'==1 | p3_3_`i'==2 | p3_3_`i'==3 | p3_3_`i'==4 | p3_3_`i'==34 | p3_3_`i'==5 | p3_3_`i'==6 | p3_3_`i'==7 | p3_3_`i'==8 | p3_3_`i'==9 |
						p3_3_`i'==10 | p3_3_`i'==11 | p3_3_`i'==13 | (p3_3_`i'==14 & p3_2_`i'>2) | p3_3_`i'==15 | p3_3_`i'==97;
};

gen vhousing=0;
*gen vcarloan=0;
gen vbusloan=0;
gen vrestbis=0;

replace vhousing=vhousesec;
replace vrestbis=vhouseunsec;
forvalues i=1(1)8 {;
*replace vcarloan=vcarloan + p3_6_`i' if p3_3_`i'==2;
replace vbusloan=vbusloan + p3_6_`i'  if p3_3_`i'==12;
replace vhousing=vhousing + p3_6_`i' if p3_3_`i'==14 & p3_2_`i'<=2;
replace vrestbis=vrestbis + p3_6_`i' if p3_3_`i'==1 | p3_3_`i'==2 | p3_3_`i'==3 | p3_3_`i'==4 | p3_3_`i'==34 | p3_3_`i'==5 | p3_3_`i'==6 | p3_3_`i'==7 | p3_3_`i'==8 | p3_3_`i'==9 |
						p3_3_`i'==10 | p3_3_`i'==11 | p3_3_`i'==13 | (p3_3_`i'==14 & p3_2_`i'>2) | p3_3_`i'==15 | p3_3_`i'==97;;
};

 ******************* INTEREST RATES *************************;
* Main residence;
forvalues i=1(1)4{;
*rename p2_9_`i' loantypemresid_`i' /* 1-mortgage, 2- othsecured, 3- personal, 4- credit line, 5- deferred, 6- advances, 7- friends family, 97- other, 98- don't know missing */;
rename p2_13_`i' loanratemresid_`i';
rename p2_14_`i' loanfixmresid_`i';
replace loanfixmresid_`i'=1 if loanfixmresid_`i'==22;
replace loanfixmresid_`i'=0 if loanfixmresid_`i'==11;
};

* Other properties (up to 3 additional properties and 3 loans for each one);
forvalues a=1(1)3{ /*property*/;
forvalues i=1(1)3{ /*loan*/;

*rename p2_52_`a'_`i' loantypeothprop_`a'_`i' /* 1-mortgage, 2- othsecured, 3- personal, 4- credit line, 5- deferred, 6- advances, 7- friends family, 97- other, 98- don't know missing */;
rename p2_56_`a'_`i' loanrateothprop_`a'_`i';
rename p2_57_`a'_`i' loanfixothprop_`a'_`i';
replace loanfixothprop_`a'_`i'=1 if loanfixothprop_`a'_`i'==22;
replace loanfixothprop_`a'_`i'=0 if loanfixothprop_`a'_`i'==11;
};
};

* Other loans;
forvalues i=1(1)8{;
*rename p3_2_`i' loantypeother_`i' /* 1-mortgage, 2- othsecured, 3- personal, 4- credit line, 5- deferred, 6- advances, 7- friends family, 97- other, 98- don't know missing */;
rename p3_7_`i' loanrateother_`i';
rename p3_8_`i' loanfixother_`i';
replace loanfixother_`i'=1 if loanfixother_`i'==22;
replace loanfixother_`i'=0 if loanfixother_`i'==11;
};

* Credit card;
rename p8_5c int_credcard;

*************************** INTEREST RATES *******************************;
******* Housing ********;
gen int_housing=0;
forvalues i=1(1)4{;
replace int_housing=int_housing+loanratemresid_`i'*p2_12_`i' if p2_9_`i'<=2; 
};

forvalues a=1(1)3 {;
forvalues i=1(1)3 {;
replace int_housing=int_housing+loanrateothprop_`a'_`i'*p2_55_`a'_`i' if  p2_52_`a'_`i'<=2;
};
};

forvalues i=1(1)8{;
replace int_housing=int_housing+loanrateother_`i'*p3_6_`i' if p3_3_`i'==14 & p3_2_`i'<=2;
};
replace p2_55_4=0 if p2_55_4==.;
replace int_housing=int_housing/(vhousing-p2_55_4);

******** Business *******;
gen int_busloan=0;
forvalues i=1(1)8{;
replace int_busloan=int_busloan+loanrateother_`i'*p3_6_`i' if p3_3_`i'==12;
};

replace int_busloan=int_busloan/vbusloan;

********* Other *********;
gen int_restbis=0;
forvalues i=1(1)4{;
replace int_restbis=int_restbis+loanratemresid_`i'*p2_12_`i' if p2_9_`i'>2 & p2_9_`i'<=97; 
};

forvalues a=1(1)3 {;
forvalues i=1(1)3 {;
replace int_restbis=int_restbis+loanrateothprop_`a'_`i'*p2_55_`a'_`i' if  p2_52_`a'_`i'>2 & p2_52_`a'_`i'<=97;
};
};

forvalues i=1(1)8{;
replace int_restbis=int_restbis+loanrateother_`i'*p3_6_`i'  if p3_3_`i'==1 | p3_3_`i'==2 | p3_3_`i'==3 | p3_3_`i'==4 | p3_3_`i'==34 | p3_3_`i'==5 | p3_3_`i'==6 | p3_3_`i'==7 | p3_3_`i'==8 | p3_3_`i'==9 |
						p3_3_`i'==10 | p3_3_`i'==11 | p3_3_`i'==13 | (p3_3_`i'==14 & p3_2_`i'>2) | p3_3_`i'==15 | p3_3_`i'==97;
};
replace int_restbis=int_restbis/vrestbis;

*************** Debt Portfolio Structure ***************;
/* Housing (debt 1), busloan (portfdebt2), Credcard (debt 3), Rest (debt 4)*/; 


******* ONE DEBT ********************************************************************;
gen portfdebt1=0;
replace portfdebt1=1 if housing==1 & busloan==0 & credcard==0 & restbis==0;

gen portfdebt2=0;
replace portfdebt2=1 if housing==0 & busloan==1 & credcard==0 & restbis==0;

					
gen portfdebt3=0;
replace portfdebt3=1 if housing==0 & busloan==0 & credcard==1 & restbis==0;

gen portfdebt4=0;
replace portfdebt4=1 if housing==0 & busloan==0 & credcard==0 & restbis==1;


******* TWO DEBTS ********************************************************************;
gen portfdebt12=0;
replace portfdebt12=1 if housing==1 & busloan==1 & credcard==0 & restbis==0;

gen portfdebt13=0;
replace portfdebt13=1 if housing==1 & busloan==0 & credcard==1 & restbis==0;

gen portfdebt14=0;
replace portfdebt14=1  if housing==1 & busloan==0 & credcard==0 & restbis==1;

gen portfdebt23=0;
replace portfdebt23=1  if housing==0 & busloan==1 & credcard==1 & restbis==0;

gen portfdebt24=0;
replace portfdebt24=1  if housing==0 & busloan==1 & credcard==0 & restbis==1;


gen portfdebt34=0;
replace portfdebt34=1  if housing==0 & busloan==0 & credcard==1 & restbis==1;


**********THREE DEBTS ********************************************************************;
gen portfdebt123=0;
replace portfdebt123=1  if housing==1 & busloan==1 & credcard==1 & restbis==0;

gen portfdebt124=0;
replace portfdebt124=1  if housing==1 & busloan==1 & credcard==0 & restbis==1;

gen portfdebt134=0;
replace portfdebt134=1  if housing==1 & busloan==0 & credcard==1 & restbis==1;

gen portfdebt234=0;
replace portfdebt234=1  if housing==0 & busloan==1 & credcard==1 & restbis==1;

********* FOUR DEBTS *********************************************************************;
gen portfdebt1234=0;
replace portfdebt1234=1  if housing==1 & busloan==1 & credcard==1 & restbis==1;

*ALGUN TIPO DE DEUDA PENDIENTE;
*SOME TYPE OF OUTSTANDING DEBT;

*Para calcular la proporción de hogares que tienen algún tipo de deuda pendiente generamos una nueva variable;
*To obtain the percentage of households that have some type of outstanding debt we generate a new variable;

gen adeuda= (debtmresid==1| debtothprop==1| p3_1>0 | credcard==1);
rename adeuda anydebt;
label var anydebt "have some type of outstanding debt";

*Para calcular el valor de las deudas pendientes generamos una nueva variable;
*To obtain the value of the outstanding debt we generate a new variable;

gen vdeuda= vdebtmresid + vdebtothprop+ vmortgoth+ vpersonal+ vothdebt + vcredcard;
rename vdeuda vdebt;
label var vdebt "value of the outstanding debt";

foreach var in portfdebt1 portfdebt2 portfdebt3 portfdebt4 portfdebt12 portfdebt13 portfdebt14 portfdebt23 
 portfdebt24 portfdebt34 portfdebt123 portfdebt124 portfdebt134 portfdebt234 portfdebt1234 {;
 
 gen v`var'=.;
 replace v`var'=vdebt if `var'==1;
 
 };
 

*VARIABLES DE RIQUEZA TOTAL Y RIQUEZAS INTERMEDIAS;
*TOTAL AND INTERMEDIATE WEALTH VARIABLES;


*ACTIVOS REALES;
*REAL ASSETS;

gen actreales=0;
replace actreales=actreales+vmresid if (vmresid>0 & vmresid~=.);
replace actreales=actreales+vothprop if (vothprop>0 & vothprop~=.);
replace actreales=actreales+vjewel if (vjewel>0 & vjewel~=.);
replace actreales=actreales+valhog if (valhog>0 & valhog~=.);

rename actreales rassets;
label var rassets "Value of real assets";


*ACTIVOS FINANCIEROS;
*FINANCIAL ASSETS;

gen actfinanc=0;
replace actfinanc=actfinanc+vaccount_pay if (vaccount_pay>0 & vaccount_pay~=.);
replace actfinanc=actfinanc+vlistshare if (vlistshare>0 & vlistshare~=.);
replace actfinanc=actfinanc+vunlist if (vunlist>0 & vunlist~=.);
replace actfinanc=actfinanc+vfixsec if (vfixsec>0 & vfixsec~=.);
replace actfinanc=actfinanc+allf if (allf>0 & allf~=.);
replace actfinanc=actfinanc+p4_43 if (p4_43>0 & p4_43~=.);
replace actfinanc=actfinanc+vaccount_nopay if (vaccount_nopay>0 & vaccount_nopay~=.);
replace actfinanc=actfinanc+vpenplan if (vpenplan>0 & vpenplan~=.);
replace actfinanc=actfinanc+vlifeinsur if (vlifeinsur>0 & vlifeinsur~=.);
replace actfinanc=actfinanc+vcreditor if (vcreditor>0 & vcreditor~=.);


rename actfinanc fassets;
label var fassets "Value of financial assets";

*RIQUEZA BRUTA;
*GROSS WEALTH;

gen riquezabr=0;
replace riquezabr=riquezabr+rassets+fassets;

rename riquezabr gwealth;
label var gwealth "Gross Wealth";

*RIQUEZA NETA=RIQUEZA BRUTA-DEUDAS;
*NET WEALTH=GROSS WEALTH-DEBTS;

gen riquezanet=gwealth-vdebt;
rename riquezanet nwealth;
label var nwealth "Net Wealth";

*CUADRO 6: VALOR TIPOS DE DEUDA SEGUN OBJETIVO DE LA DEUDA;
*TABLE 6: VALUE OF DEBTS BY PURPOSE OF DEBTS;

*TBD;

*Para deuda por compra vivienda principal usamos dvivpral;
*For debt originated by home purchase we use dvivpral;

*Para deuda por compra otras prop. inmobiliarias usamos deuoprop;
*For debt originated by purchase of other real estate properties we use deuoprop;

*Para deudas pendientes por el resto de deudas (garantia real, credito personal, otras deudas, deudas con tarjetas de credito) usaremos deuotros;
*For other outstanding debts (secured loans, personal loans, credit card balances and other debts) we use deuotros;

*CUADRO 8: RATIOS INDIVIDUALES DE DEUDA;
*TABLE 8: INDIVIDUAL DEBT RATIOS;

*PAGOS POR DEUDAS;
*DEBT PAYMENTS;

*Para el total de pagos por deudas generamos la variable pagodeuda;
*For total debt payments we generate the variable pagodeuda;

gen pagodeuda=0;
gen pagodeuviv=0;
gen pagodeuoprop=0;
gen pagodeusec3=0;
set output error;
forvalues j=1/4 {;
	display _newline(1) `j';
	gen np2_18_`j'=p2_18_`j';
	replace np2_18_`j'=0 if (p2_18_`j'==.|p2_18_`j'<0);
	replace pagodeuviv=pagodeuviv+np2_18_`j';
			};

forvalues j=1/8 {;
	display _newline(1) `j';
	gen np3_11_`j'=p3_11_`j';
	replace np3_11_`j'=0 if (p3_11_`j'==.|p3_11_`j'<0);
	replace pagodeusec3=pagodeusec3+np3_11_`j';
			};

forvalues m=1/3   {;
	forvalues j=1/3 {;
	display _newline(1) `m' `j';
		gen np2_61_`m'_`j'=p2_61_`m'_`j';
	replace np2_61_`m'_`j'=0 if (p2_61_`m'_`j'==.|p2_61_`m'_`j'<0);
	replace pagodeuoprop=pagodeuoprop+np2_61_`m'_`j';
			};
};
set output proc;

gen np2_61_4=p2_61_4;
replace np2_61_4=0 if (p2_61_4==. | p2_61_4<0);
replace pagodeuoprop=pagodeuoprop+np2_61_4;

gen np8_5b=p8_5b;
replace np8_5b=0 if (p8_5b==. | p8_5b<0);
gen pagotarjeta=np8_5b;
	
replace pagodeuda=pagodeuviv+pagodeuoprop+pagodeusec3 + pagotarjeta;


rename pagodeuda paydebt;
label var paydebt "Monthly total debt payments";
rename pagodeuviv paydresid;
label var paydresid "Monthly residential debt payments";
rename pagodeuoprop payothprop;
label var payothprop "Monthly other properties debt payments";
rename pagodeusec3 paypersonal;
label var paypersonal "Monthly personal debt payments";

*CUADRO 9: GASTO EN BIENES DURADEROS Y NO DURADEROS Y TENENCIA DE BIENES DURADEROS;
*TABLE 9: EXPENDITURE ON NON-DURABLE AND DURABLE GOODS AND HOLDINGS OF DURABLE GOODS;

*1.-GASTO ANUAL BIENES VARIOS (% y mediana);
*1.-ANNUAL EXPENDITURE ON DIFFERENT GOODS (% and median);

*Gasto anual en Alimentacion;
*Annual expenditure on Food;

gen frec=12 if p9_2b==2;
replace frec=12*4.3 if p9_2b==1;
gen alim=0;
replace alim=alim+(p9_2*frec) if p9_2>0;
rename alim food;
label var food "Annual expenditure on Food";

*Gasto anual en Otros bienes no duraderos;
*Annual expenditure on Other non-durable goods;

gen nodur=0;
replace nodur=nodur+ (p9_1*12)-food if p9_1>0;
label var nodur "Annual expenditure on Other non-durable goods";

*Gasto anual en vehiculos (si/no y valor);
*Annual expenditure on vehicles (yes/no and value);

*Para decisión adquisición vehículos;
*For the decision to buy vehicles;

gen gvehic=(p2_73==1 | p2_77==1);
rename gvehic vehic;
label var vehic "household purchased a vehicle that year";

*Para valor adquisicion vehículos;
*For the value of vehicles purchased;

gen gimpvehic=0;
replace gimpvehic=gimpvehic+p2_74 if (p2_74>0 & p2_74~=.);
replace gimpvehic=gimpvehic+p2_78 if (p2_78>0 & p2_78~=.);
rename gimpvehic vvehicle;
label var vvehicle "value of vehicles purchased";

*Gasto anual en Otros bienes duraderos (si/no y valor);
*Annual expenditure on Other durable goods (yes/no and value);


*Para decisión adquisición bienes duraderos utilizamos la p2_69;
*For the decision to buy durable goods we use the variable p2_69;

*Para valor adquisicion bienes duraderos usamos p2_70;
*For the value of durable goods purchases we use p2_70;


*2.- PARA TENENCIA DURADEROS (% Y MEDIANA);
*2.- FOR HOLDINGS OF DURABLE GOODS (% AND MEDIAN);

*Tenencia vehiculos;
*Holding of vehicles;

*Proporcion con vehiculos;
*Percentage with vehicles;

gen tvehic=(p2_72>0|p2_76>0);

*Mediana para los que tienen;
*Median for the ones who have; 

gen timpvehic=0;
replace timpvehic = timpvehic + p2_75 if (p2_72>0 & p2_75>0 & p2_75~=.);
replace timpvehic = timpvehic + p2_79 if ( p2_76>0 &  p2_79>0 & p2_79~=.);

*Tenencia Otros bienes duraderos;
*Holding of Other durable goods;

*Para valor tenencia bienes duraderos usamos p2_71;
*For the value of durable goods holdings we use p2_71;


*VARIABLES DE CARACTERISTICAS DE LOS HOGARES QUE FIGURAN EN LOS CUADROS;
*VARIABLES OF HOUSEHOLD CHARACTERISTICS THAT APPEAR IN THE TABLES;

*1.- DEFINICIÓN DE PERCENTILES (i) RENTA TOTAL HOGAR Y (ii) RIQUEZA NETA;
*1.- DEFINITION OF PERCENTILES (i) HOUSEHOLD TOTAL INCOME AND (ii) NET WEALTH; 
rename renthog hhincome /* annual 2001 for 2002 wave, 2004 (2005 wave), 2007 (2008 wave) */;
_pctile hhincome [pweight=facine3], p(20,40,60,80,90);
return list;

gen percrent=1 if (hhincome<r(r1));
replace percrent=2 if (hhincome>=r(r1) & hhincome<r(r2));
replace percrent=3 if (hhincome>=r(r2) & hhincome<r(r3));
replace percrent=4 if (hhincome>=r(r3) & hhincome<r(r4));
replace percrent=5 if (hhincome>=r(r4) & hhincome<r(r5));
replace percrent=6 if  hhincome>=r(r5);


_pctile nwealth [pweight=facine3], p(25,50,75,90);
return list;

gen percriq=1 if (nwealth<r(r1));
replace percriq=2 if (nwealth>=r(r1) & nwealth<r(r2));
replace percriq=3 if (nwealth>=r(r2) & nwealth<r(r3));
replace percriq=4 if (nwealth>=r(r3) & nwealth<r(r4));
replace percriq=5 if  nwealth>=r(r4);

gen percriq25=1 if nwealth==r(r1);
gen percriq50=1 if nwealth==r(r2);
gen percriq75=1 if nwealth==r(r3);

foreach var in vhousing vbusloan vcredcard vrestbis {;
gen nwealth_`var'=nwealth +`var';

gen percriq_`var'25=1 if nwealth_`var'==r(r1);
gen percriq_`var'50=1 if nwealth_`var'==r(r2);
gen percriq_`var'75=1 if nwealth_`var'==r(r3);
};
*2.- NOMBRE Y CODIFICACIÓN DE LAS VARIABLES QUE RECOGEN CARACTERÍSTICAS SOCIO-DEMOGRÁFICAS DEL HOGAR QUE APARECEN EN LOS CUADROS;
*2.- NAME AND CODING OF THE VARIABLES THAT CONTAIN HOUSEHOLDS SOCIO-DEMOGRAPHIC CHARACTERISTICS THAT APPEAR IN THE TABLES;

*EDAD DEL CABEZA DE FAMILIA;
*AGE OF HOUSEHOLD HEAD;
*bage: toma valores 1 a 6, <35, >34 & <45, >44 & <55, >54 & <65, >64 & <75, >74;
*bage: takes values 1 to 6, <35, >34 & <45, >44 & <55, >54 & <65, >64 & <75, >74;

*SITUACION LABORAL DEL CABEZA DE FAMILIA;
*LABOUR MARKET SITUATION OF HOUSEHOLD HEAD;
*nsitlabdom: toma valores 1 a 4, empleado por cuenta ajena, empleado por cuenta propia, jubilado, otro tipo de inactivo o parado;
*nsitlabdom: takes values 1 to 4, employee, self-employed, retired, other type of economic inactivity or unemployed;

*NIVEL DE EDUCACION DEL CABEZA DE FAMILIA;
*LEVEL OF EDUCATION OF HOUSEHOLD HEAD;
*neducdom: toma valores 1 a 3, inferior a bachillerato, bachillerato, estudios universitarios;
*neducdom: takes values 1 to 3, below secondary education, secondary education, University education;

*REGIMEN DE TENENCIA DE LA VIVIENDA PRINCIPAL;
*STATUS OF MAIN RESIDENCE;
*np2_1: toma valores 1 y 0, propiedad, otros regímenes de tenencia;
*np2_1: takes values 1 and 0, ownership, other;


*NUMERO DE ADULTOS EN EL HOGAR TRABAJANDO;
*NUMBER OF ADULT HOUSEHOLD MEMBERS WORKING;
*nnumadtrab: toma valores 0 a 3, ninguno, uno, dos, tres o más;
*nnumadtrab: takes values 0 to 3, none, one, two, three or more;


*NUMERO DE MIEMBROS EN EL HOGAR;
*NUMBER OF HOUSEHOLD MEMBERS;
*np1: toma valores 1 a 5, uno, dos, tres, cuatro, cinco o más.
*np1: takes values 1 to 5, one, two, three, four, five or more.


**** Reference person (designed by the household) variables ****;
/* From questionnaire: "The reference person is the person, or one of the persons, responsible for the accommodation. It will normally be the person in the 
household who chiefly deals with the financial issues." */;

rename p1 members /* Number of household members */;




forvalues i = 1(1)9 {;
	rename p1_1_`i' sex`i' /* Male (1), Female (0)*/;
	replace sex`i'=0 if sex`i'==2;
	rename p1_2b_`i' nac`i';
	rename p1_3_`i' relref`i';
	rename p1_5_`i' educ`i' /* Education level (see questionnaire)*/;
	rename p1_7_`i' health`i' /* Health status of reference person: 1-very good, 2-good, 3-acceptable, 4-poor, 5-very poor */;
	rename p6_1c1_`i' employee`i';
	rename p6_1c2_`i' selfemployed`i';
	rename p6_1c3_`i' unemployed`i';
	rename p6_1c4_`i' retiree`i';
	rename p6_1c5_`i' disable`i';
	rename p6_1c6_`i' student`i';
	rename p6_1c7_`i' housew`i';
	rename p6_1c8_`i' oth_inact`i';
	rename p6_4_`i' typejob`i';
	gen bankjob`i'=0;
	replace bankjob`i'=1 if typejob`i'==9;

	};

	forvalues i = 1(1)9 {;
	gen ageaux`i'=0;
	replace ageaux`i'=2008-nac`i';
	gen child`i'=0;
	replace child`i'=1 if ageaux`i'<16 ;
	};

cap drop ageaux*;

egen nchilds=rowtotal(child1-child9);
	
gen sex=0;
gen nac=0;
gen educ=0;
gen health=0;
gen employee=0;
gen selfemployed=0;
gen unemployed=0;
gen retiree=0;
gen disable=0;
gen student=0;
gen housew=0;
gen oth_inact=0;
gen bankjob=0;

* Dummy variable for university degree;
* Ordinary university degree / Training leading to an officially recognised professional specialisation;
* Postgraduate university education ;

forvalues i = 1(1)9 {;
gen univ`i'=0;
replace univ`i'=1 if educ`i'==10 | educ`i'==11 | educ`i'==12;
};

gen univ=0;


/* Marital status reference person: married if any other person in the household declares to be the couple of the head */;

gen married=0;

forvalues i = 2(1)9 {;
	replace married=1 if relref`i'==2;
	};

gen couplewith=(married==1 & nchilds>0);
gen couplewithout=(married==1 & nchilds==0);
gen singlewith=(married==0 & nchilds>0);
gen singlewithout=(married==0 & nchilds==0);	
	
rename p1_4_1 marital1 /* Marital status reference person: 1-single, 2-married, 3-de facto partner 
						4-separated, 5-divorced, 6-widowed */;

/* With the information of the other members, create variables that summarize the familiar characteristics */;

*gen othcoup=0 /* to identify those hh where household head is not the reference person in the survey */;

*CRITERIUM: Take the main earner in employees. Otherwise, take the male;

* Compute wage for each member of the houysehold;
forvalues i=1(1)9{;
replace student`i'=0 if oth_inact`i'==1 | disable`i'==1 | housew`i'==1 | unemployed`i'==1 | retiree`i'==1 | selfemployed`i'==1 | employee`i'==1;
replace oth_inact`i'=0 if disable`i'==1 | housew`i'==1 | unemployed`i'==1 | retiree`i'==1 | selfemployed`i'==1 | employee`i'==1;
replace disable`i'=0 if housew`i'==1 | unemployed`i'==1 | retiree`i'==1 | selfemployed`i'==1 | employee`i'==1;
replace housew`i'=0 if unemployed`i'==1 | retiree`i'==1 | selfemployed`i'==1 | employee`i'==1;
replace unemployed`i'=0 if retiree`i'==1 | selfemployed`i'==1 | employee`i'==1;
replace retiree`i'=0 if selfemployed`i'==1 | employee`i'==1;
replace selfemployed`i'=0 if employee`i'==1;
gen ageaux`i'=0;
replace ageaux`i'=2008-nac`i';
replace retiree`i'=1 if (housew`i'==1 | oth_inact`i'==1 | disable`i'==1 | student`i'==1) & ageaux`i'>=65 /* Take this persons as retired */;
replace housew`i'=0 if retiree`i'==1;
replace oth_inact`i'=0 if retiree`i'==1;
replace disable`i'=0 if retiree`i'==1;
replace student`i'=0 if retiree`i'==1;
};

forvalues i=1(1)9{;
	egen wage`i'=rowtotal(p6_14_`i'_*);
	gen mainearner`i'=0;
		replace employee`i'=1 if wage`i'>0 & student`i'==0 & oth_inact`i'==0 & disable`i'==0 & housew`i'==0 & 
	unemployed`i'==0 & retiree`i'==0 & selfemployed`i'==0 & employee`i'==0;
	};
	
replace mainearner1=1;

forvalues i=2(1)9{;
	replace mainearner`i'=1 if wage`i'>wage1 & relref`i'==2 & employee`i'==1;
	replace mainearner1=0   if wage`i'>wage1 & relref`i'==2 & employee`i'==1;	
	};	

forvalues i =2(1)9 {;
	gen othcoup`i'=0;
	replace othcoup`i'=1 if married==1 & sex1==0 & sex`i'==1 & relref`i'==2;	
	replace othcoup`i'=1 if married==1 & mainearner`i'==1 & relref`i'==2;
	replace othcoup`i'=1 if married==1 & (housew==1 | student==1) & 
		(unemployed`i'==1 | retiree`i'==1 | selfemployed`i'==1) & relref`i'==2 /*Take the couple when head is housewife */;
	replace sex=sex`i' if othcoup`i'==1;
	replace nac=nac`i' if othcoup`i'==1;
	replace educ=educ`i' if othcoup`i'==1;
	replace health=health`i' if othcoup`i'==1;
	replace employee=employee`i' if othcoup`i'==1;
	replace selfemployed=selfemployed`i' if othcoup`i'==1;
	replace unemployed=unemployed`i' if othcoup`i'==1;
	replace student=student`i' if othcoup`i'==1;
	replace housew=housew`i' if othcoup`i'==1;
	replace oth_inact=oth_inact`i' if othcoup`i'==1;
	replace retiree=retiree`i' if othcoup`i'==1;
	replace health=health`i' if othcoup`i'==1;
	replace univ=univ`i' if othcoup`i'==1;
	replace bankjob=bankjob`i' if othcoup`i'==1;
	};

egen othcoup=rowtotal(othcoup*);

replace sex=sex1 if othcoup==0;
replace nac=nac1 if othcoup==0;
replace educ=educ1 if othcoup==0;
replace health=health1 if othcoup==0;
replace employee=employee1 if othcoup==0;
replace selfemployed=selfemployed1 if othcoup==0;
replace retiree=retiree1 if othcoup==0;
replace disable=disable1 if othcoup==0;
replace student=student1 if othcoup==0;
replace housew=housew1 if othcoup==0;
replace oth_inact=oth_inact1 if othcoup==0;
replace unemployed=unemployed1 if othcoup==0;
replace univ=univ1 if othcoup==0;
replace bankjob=bankjob1 if othcoup==0;

/* Gen dummy to identify status of the couple */;
gen pemployee=0;
gen pselfemployed=0;
gen punemployed=0;
gen pretiree=0;
gen pdisable=0;
gen pstudent=0;
gen phousew=0;
gen poth_inact=0;
gen puniv=0;
gen pnac=0;

forvalues i=2(1)9 {;
	replace punemployed=1 if othcoup`i'==0 & unemployed`i'==1 & relref`i'==2;
	replace pemployee=1 if othcoup`i'==0 & employee`i'==1 & relref`i'==2;
	replace pretiree=1 if othcoup`i'==0 & retiree`i'==1 & relref`i'==2;
	replace pselfemployed=1 if othcoup`i'==0 & selfemployed`i'==1 & relref`i'==2;
	replace pdisable=1 if othcoup`i'==0 & disable`i'==1 & relref`i'==2;
	replace pstudent=1 if othcoup`i'==0 & student`i'==1 & relref`i'==2;
	replace phousew=1 if othcoup`i'==0 & housew`i'==1 & relref`i'==2;
	replace poth_inact=1 if othcoup`i'==0 & oth_inact`i'==1 & relref`i'==2;
	replace puniv=1 if othcoup`i'==0 & univ`i'==1 & relref`i'==2;
	replace pnac=1 if othcoup`i'==0 & nac`i'==1 & relref`i'==2;

	replace punemployed=1 if othcoup`i'==1 & unemployed1==1 & relref`i'==2;
	replace pemployee=1 if othcoup`i'==1 & employee1==1 & relref`i'==2;
	replace pretiree=1 if othcoup`i'==1 & retiree1==1 & relref`i'==2;
	replace pselfemployed=1 if othcoup`i'==1 & selfemployed1==1 & relref`i'==2;
	replace pdisable=1 if othcoup`i'==1 & disable1==1 & relref`i'==2;
	replace pstudent=1 if othcoup`i'==1 & student1==1 & relref`i'==2;
	replace phousew=1 if othcoup`i'==1 & housew1==1 & relref`i'==2;
	replace poth_inact=1 if othcoup`i'==1 & oth_inact1==1 & relref`i'==2;
	replace puniv=1 if othcoup`i'==1 & univ1==1 & relref`i'==2;
	replace pnac=1 if othcoup`i'==1 & nac1==1 & relref`i'==2;
	};
* Define other reference person for housew/student households: specifically, take as reference person those sons or daughters that are
main earners;

egen maxw=rowmax(wage1 wage2 wage3 wage4 wage5 wage6 wage7 wage8 wage9);

forvalues i=2(1)9{;
		gen oth_member`i'=0;
		replace oth_member`i'=1 if (housew==1 | student==1) & wage`i'==maxw & maxw>0;
		replace employee`i'=1 if oth_member`i'==1;
		replace sex=sex`i' if oth_member`i'==1;
		*replace psex=0 if oth_member`i'==1 /* Assume has no couple */;
		replace nac=nac`i' if oth_member`i'==1;
		replace pnac=0 if oth_member`i'==1 /* Assume has no couple */;
		replace educ=educ`i' if oth_member`i'==1;
		*replace peduc=0 if oth_member`i'==1 /* Assume has no couple */;
		replace health=health`i' if oth_member`i'==1;
		*replace phealth=0 if oth_member`i'==1 /* Assume has no couple */;
		replace employee=employee`i' if oth_member`i'==1;
		replace pemployee=0 if oth_member`i'==1 /* Assume has no couple */;
		replace selfemployed=selfemployed`i' if oth_member`i'==1;
		replace pselfemployed=0 if oth_member`i'==1 /* Assume has no couple */;
		replace retiree=retiree`i' if oth_member`i'==1;
		replace pretiree=0 if oth_member`i'==1 /* Assume has no couple */;
		replace disable=disable`i' if oth_member`i'==1;
		replace pdisable=0 if oth_member`i'==1 /* Assume has no couple */;
		replace student=student`i' if oth_member`i'==1;
		replace pstudent=0 if oth_member`i'==1 /* Assume has no couple */;
		replace housew=housew`i' if oth_member`i'==1;
		replace phousew=0 if oth_member`i'==1 /* Assume has no couple */;
		replace oth_inact=oth_inact`i' if oth_member`i'==1;
		replace poth_inact=0 if oth_member`i'==1 /* Assume has no couple */;
		replace unemployed=unemployed`i' if oth_member`i'==1;
		replace punemployed=0 if oth_member`i'==1 /* Assume has no couple */;
		replace univ=univ`i' if oth_member`i'==1;
		replace puniv=0 if oth_member`i'==1 /* Assume has no couple */;
		};	

egen auxoth=rowtotal(oth_member*);
		
/* Choose other household member if there are no employees*/;
forvalues i=2(1)9{;
		gen oth2_member`i'=0;
		replace oth2_member`i'=1 if (housew==1 | student==1) & auxoth==0 & selfemployed`i'==1;
		replace selfemployed`i'=1 if oth2_member`i'==1;
		replace sex=sex`i' if oth2_member`i'==1;
		*replace psex=0 if oth_member`i'==1 /* Assume has no couple */;
		replace nac=nac`i' if oth2_member`i'==1;
		replace pnac=0 if oth2_member`i'==1 /* Assume has no couple */;
		replace educ=educ`i' if oth2_member`i'==1;
		*replace peduc=0 if oth_member`i'==1 /* Assume has no couple */;
		replace health=health`i' if oth2_member`i'==1;
		*replace phealth=0 if oth_member`i'==1 /* Assume has no couple */;
		replace employee=employee`i' if oth2_member`i'==1;
		replace pemployee=0 if oth2_member`i'==1 /* Assume has no couple */;
		replace selfemployed=selfemployed`i' if oth2_member`i'==1;
		replace pselfemployed=0 if oth2_member`i'==1 /* Assume has no couple */;
		replace retiree=retiree`i' if oth2_member`i'==1;
		replace pretiree=0 if oth2_member`i'==1 /* Assume has no couple */;
		replace disable=disable`i' if oth2_member`i'==1;
		replace pdisable=0 if oth2_member`i'==1 /* Assume has no couple */;
		replace student=student`i' if oth2_member`i'==1;
		replace pstudent=0 if oth2_member`i'==1 /* Assume has no couple */;
		replace housew=housew`i' if oth2_member`i'==1;
		replace phousew=0 if oth2_member`i'==1 /* Assume has no couple */;
		replace oth_inact=oth_inact`i' if oth2_member`i'==1;
		replace poth_inact=0 if oth2_member`i'==1 /* Assume has no couple */;
		replace unemployed=unemployed`i' if oth2_member`i'==1;
		replace punemployed=0 if oth2_member`i'==1 /* Assume has no couple */;
		replace univ=univ`i' if oth2_member`i'==1;
		replace puniv=0 if oth2_member`i'==1 /* Assume has no couple */;
		};	

gen bhealth=0;
replace bhealth=1 if health>=4;
		
egen auxoth2=rowtotal(oth2_member*);

egen aux=rowtotal(employee selfemployed unemployed retiree disable student housew oth_inact);
keep if aux==1;
gen age=2008-nac;
replace age=age/10;

** Age dummies **;
gen age1=0;
replace age1=1 if age>=3 & age<3.5;

gen age2=0;
replace age2=1 if age>=3.5 & age<4;

gen age3=0;
replace age3=1 if age>=4 & age<4.5;

gen age4=0;
replace age4=1 if age>=4.5 & age<5;

gen age5=0;
replace age5=1 if age>=5 & age<5.5;

gen age6=0;
replace age6=1 if age>=5.5 & age<6;

gen age7=0;
replace age7=1 if age>=6 & age<6.5;

gen age8=0;
replace age8=1 if age>=6.5 & age<7;

gen age9=0;
replace age9=1 if age>=7 & age<7.6;

gen age_inst=0;
replace age_inst=1 if age1==1;
replace age_inst=2 if age2==1;
replace age_inst=3 if age3==1;
replace age_inst=4 if age4==1;
replace age_inst=5 if age5==1;
replace age_inst=6 if age6==1;
replace age_inst=7 if age7==1;
replace age_inst=8 if age8==1;
replace age_inst=9 if age9==1;


gen agesq=age^2;

gen page=2005-nac;
replace page=page/10;

** page dummies **;
gen page1=0;
replace page1=1 if page>=3 & page<3.5;

gen page2=0;
replace page2=1 if page>=3.5 & page<4;

gen page3=0;
replace page3=1 if page>=4 & page<4.5;

gen page4=0;
replace page4=1 if page>=4.5 & page<5;

gen page5=0;
replace page5=1 if page>=5 & page<5.5;

gen page6=0;
replace page6=1 if page>=5.5 & page<6;

gen page7=0;
replace page7=1 if page>=6 & page<6.5;

gen page8=0;
replace page8=1 if page>=6.5 & page<7;

gen page9=0;
replace page9=1 if page>=7 & page<7.6;

gen page_inst=0;
replace page_inst=1 if page1==1;
replace page_inst=2 if page2==1;
replace page_inst=3 if page3==1;
replace page_inst=4 if page4==1;
replace page_inst=5 if page5==1;
replace page_inst=6 if page6==1;
replace page_inst=7 if page7==1;
replace page_inst=8 if page8==1;
replace page_inst=9 if page9==1;

gen pagesq=page^2;




/* Drop multiple-unrelated households */;

egen minval=rowmin(relref*);
replace minval=0 if minval==.;

gen madult=0;
replace madult=1 if minval==9 & (year==2002 | year==2005);
replace madult=1 if minval==12 & (year==2008 | year==2011);


********************************************;
rename p2_3 instal /* Year of house purchasing (assume to be the same as instalment) */;
rename p2_4 price_a /* Purchasing price */;
rename p2_5 price_b /* Price of hypothetical sell */;


		  
 ******************* Application for loans ********************;

rename p3_14 nreject /* number of applications rejected */;

/* Totally reject loan application (any) */;
gen reject=0;
replace reject=1 if nreject>0;
replace reject=0 if nreject==.;

forvalues i=1(1)5 {;
	rename p3_13s`i' rnoappl`i' /* Reasons of not applying for a loan */;
	rename p3_15s`i' rreject`i' /* Reasons of rejecting */;
	};

rename p3_12 napplic /* Number of no applications made in last two years */;

/* Discouraged borrowers: refuse to apply for a loan because it would be turned down (any member of the household. Exclude debt holders */;
gen discour=0;
replace discour=1 if (rnoappl1==4 | rnoappl2==4 | rnoappl3==4 | rnoappl4==4 | rnoappl5==4) & anydebt==0 & napplic==0;


/* Applicant: whether the household made any loan application or refused beacuse of sure rejecting */;
gen applic=0;
replace applic=1 if napplic>0 | discour==1 | anydebt==1;
* replace applic=0 if ration==0 & anydebt==0 /* Applied, accepted but did not take the loan (we think they took the loan and repaid the debt) */;

* gen applic_non_disc=0;
* replace applic_non_disc=1 if napplic>0 | anydebt==1;


rename p3_16 npartrej /* # times granted smaller amount than asked for */;



/* Partially rejected loan application (any) */;
gen partrej=0;
replace partrej=1 if npartrej>0;
replace partrej=0 if npartrej==.;

gen totpartrej=0;
replace totpartrej=1 if (reject==1 | partrej==1);
replace totpartrej=1 if discour==1;
*replace totpartrej=0 if anydebt==1;

/* Rationed: discouraged or reject totally or partially */;
gen ration2=0;
replace ration2=1 if discour==1 | partrej==1 | reject==1;
replace ration2=0 if ration2==.;
*replace ration2=0 if anydebt==1;

/* Rationed: discouraged or totally rejected */;
gen ration=0;
replace ration=1 if discour==1 | reject==1;
replace ration=0 if ration==.;
*replace ration=0 if anydebt==1;

*replace anydebt=1 if applic==1 & anydebt==0 & ration==0 /* Applied, borrowed and repaid, and report zero borrowing */;


/* Another definition is made 200 lines or more in advanced (guess that it was done in Venice)
/* Partially and Totally rationed */;

gen totpartrej=0;
replace totpartrej=1 if reject==1 | partrej==1;
*/;


						   
**************** INCOME *********************;
replace hhincome=hhincome/acpi*100;
gen lincome=log(1+hhincome);
replace hhincome=hhincome/10000;
gen hhincomesq=(hhincome^2)/10000;

rename mrenthog mhhincome /* month oct2002 - may2003 (2002), nov2005 - may2006 (2005), nov2008 - jun2009 (2008) */;
replace mhhincome=mhhincome/mcpi*100;
gen mhhincomesq=mhhincome^2;


************** FINANCIAL HELP FROM RELATIVES AND FRIENDS *******************;
/*monetary assistance from friends or family members outside the
household, or from a partner no longer living in the household*/;

rename p6_59 finhelp;
replace finhelp=0 if finhelp==2;

rename p6_60 amounthelp;
replace amounthelp=amounthelp/mcpi*100;

************ ARREARS *****************;

/* In the last twelve months have you had any financial
difficulties which resulted in your delaying the payment of any of
your debts? */;

gen arrears=0;
replace arrears=1 if p9_16==1;

*replace anydebt=1 if arrears==1;
replace applic=1 if anydebt==1;
*replace ration=0 if arrears==1;
replace discour=0 if anydebt==1;

gen applic_non_disc=0;
replace applic_non_disc=1 if applic==1 & discour==0;

gen repay=.;
replace repay=1 if arrears==0 & anydebt==1;
replace repay=0 if arrears==1;


* Risk Aversion;
rename p9_11 riskaver;

gen risklot=.;
replace risklot=0 if riskaver==2 | riskaver==3 | riskaver==4;
replace risklot=1 if riskaver==1;

gen riskfair=.;
replace riskfair=0 if riskaver==1 | riskaver==3 | riskaver==4;
replace riskfair=1 if riskaver==2;

gen risksome=.;
replace risksome=0 if riskaver==1 | riskaver==2 | riskaver==4;
replace risksome=1 if riskaver==3;

gen norisk=.;
replace norisk=0 if riskaver==1 | riskaver==2 | riskaver==3;
replace norisk=1 if riskaver==4;

******** Dummies for hhincome ********;
_pctile hhincome, p(20,40,60,80);
scalar r1=r(r1);
scalar r2=r(r2);
scalar r3=r(r3);
scalar r4=r(r4);

gen hhincome1=0;
replace hhincome1=1 if hhincome<scalar(r1);

gen hhincome2=0;
replace hhincome2=1 if hhincome>=scalar(r1) & hhincome<scalar(r2);

gen hhincome3=0;
replace hhincome3=1 if hhincome>=scalar(r2) & hhincome<scalar(r3);

gen hhincome4=0;
replace hhincome4=1 if hhincome>=scalar(r3)  & hhincome<scalar(r4);

gen hhincome5=0;
replace hhincome5=1 if hhincome>scalar(r4);

gen inc_inst=0;
replace inc_inst=1 if hhincome1==1;
replace inc_inst=2 if hhincome2==1;
replace inc_inst=3 if hhincome3==1;
replace inc_inst=4 if hhincome4==1;

*********** Dummies for income II ************;
replace hhincome=hhincome*10000;

gen hh1=0;
replace hh1=1 if hhincome<=15000;
gen hh2=0;
replace hh2=1 if hhincome>15000 & hhincome<=25000;
gen hh3=0;
replace hh3=1 if hhincome>25000 & hhincome<=35000;
gen hh4=0;
replace hh4=1 if hhincome>35000 & hhincome<=45000;
gen hh5=0;
replace hh5=1 if hhincome>45000 & hhincome<=57000;
gen hh6=0;
replace hh6=1 if hhincome>57000;

*/;
gen hh_inst=0;
replace hh_inst=1 if hh1==1;
replace hh_inst=2 if hh2==1;
replace hh_inst=3 if hh3==1;
replace hh_inst=4 if hh4==1;
replace hh_inst=5 if hh5==1;
replace hh_inst=6 if hh6==1;
*replace hh_inst=7 if hh7==1;
*replace hh_inst=8 if hh8==1;
*replace hh_inst=9 if hh9==1;

replace hhincome=hhincome/10000;

*********** Dummies for nwealth ************;

replace nwealth=nwealth/acpi*100;
gen lnwealth=.;
replace lnwealth=log(1+abs(nwealth)) if nwealth>=0;
replace lnwealth=-log(1+abs(nwealth)) if nwealth<0;

gen nw1=0;
replace nw1=1 if nwealth<=10000;
gen nw2=0;
replace nw2=1 if nwealth>10000 & nwealth<=80000;
gen nw3=0;
replace nw3=1 if nwealth>80000 & nwealth<=200000;
gen nw4=0;
replace nw4=1 if nwealth>200000 & nwealth<=500000;
gen nw5=0;
replace nw5=1 if nwealth>500000;


***** Generate alternative wealth variables *****;
gen housewealth= nwealth;
replace housewealth=housewealth-vmresid/acpi*100+vdebtmresid/acpi*100 if debtmresid==1;

replace housewealth=housewealth + vdebtprop1/acpi*100 - p2_39_1*(p2_37_1/100)/acpi*100 if vdebtprop1>0;
replace housewealth=housewealth + vdebtprop2/acpi*100 - p2_39_2*(p2_37_1/100)/acpi*100 if vdebtprop2>0;
replace housewealth=housewealth + vdebtprop3/acpi*100 - p2_39_3*(p2_37_1/100)/acpi*100 if vdebtprop3>0;
replace housewealth=housewealth + vdebtprop4/acpi*100 - p2_39_4*(p2_37_1/100)/acpi*100 if vdebtprop4>0;

gen lhousingw=.;
replace lhousingw=log(1+abs(housewealth)) if housewealth>=0;
replace lhousingw=-log(1+abs(housewealth)) if housewealth<0;

gen buswealth=nwealth;
replace buswealth=buswealth-valhog/acpi*100+vbusloan;

gen lbusloanw=.;
replace lbusloanw=log(1+abs(buswealth)) if buswealth>=0;
replace lbusloanw=-log(1+abs(buswealth)) if buswealth<0;

gen cardwealth=nwealth;
replace cardwealth=cardwealth+vcredcard;

gen lcredcardw=.;
replace lcredcardw=log(1+abs(cardwealth)) if cardwealth>=0;
replace lcredcardw=-log(1+abs(cardwealth)) if cardwealth<0;

gen otherwealth=nwealth;
replace otherwealth=otherwealth-vrestbis;

gen lrestbisw=.;
replace lrestbisw=log(1+abs(otherwealth)) if otherwealth>=0;
replace lrestbisw=-log(1+abs(otherwealth)) if otherwealth<0;

*********** Dummies for housing wealth ************;

gen housingw1=0;
replace housingw1=1 if housewealth<=10000;
gen housingw2=0;
replace housingw2=1 if housewealth>10000 & housewealth<=80000;
gen housingw3=0;
replace housingw3=1 if housewealth>80000 & housewealth<=200000;
gen housingw4=0;
replace housingw4=1 if housewealth>200000 & housewealth<=500000;
gen housingw5=0;
replace housingw5=1 if housewealth>500000;

*********** Dummies for business wealth ************;

gen busloanw1=0;
replace busloanw1=1 if buswealth<=10000;
gen busloanw2=0;
replace busloanw2=1 if buswealth>10000 & buswealth<=80000;
gen busloanw3=0;
replace busloanw3=1 if buswealth>80000 & buswealth<=200000;
gen busloanw4=0;
replace busloanw4=1 if buswealth>200000 & buswealth<=500000;
gen busloanw5=0;
replace busloanw5=1 if buswealth>500000;

*********** Dummies for credit card wealth ************;

gen credcardw1=0;
replace credcardw1=1 if cardwealth<=10000;
gen credcardw2=0;
replace credcardw2=1 if cardwealth>10000 & cardwealth<=80000;
gen credcardw3=0;
replace credcardw3=1 if cardwealth>80000 & cardwealth<=200000;
gen credcardw4=0;
replace credcardw4=1 if cardwealth>200000 & cardwealth<=500000;
gen credcardw5=0;
replace credcardw5=1 if cardwealth>500000;


*********** Dummies for other debts wealth ************;

gen restbisw1=0;
replace restbisw1=1 if otherwealth<=10000;
gen restbisw2=0;
replace restbisw2=1 if otherwealth>10000 & otherwealth<=80000;
gen restbisw3=0;
replace restbisw3=1 if otherwealth>80000 & otherwealth<=200000;
gen restbisw4=0;
replace restbisw4=1 if otherwealth>200000 & otherwealth<=500000;
gen restbisw5=0;
replace restbisw5=1 if otherwealth>500000;


foreach f of var * { ;
	rename `f' `f'_imp`x' ;
} ;
rename h_2008_imp`x' h2008;
drop p6*;
save wave2008_imp`x'.dta, replace;

};


cd "H:\Mi unidad\Grant_new\EFF";
use "H:\Mi unidad\Grant_new\EFF\Imputation1\wave2008_imp1.dta";
joinby h2008 using "H:\Mi unidad\Grant_new\EFF\Imputation2\wave2008_imp2";
joinby h2008 using "H:\Mi unidad\Grant_new\EFF\Imputation3\wave2008_imp3";
joinby h2008 using "H:\Mi unidad\Grant_new\EFF\Imputation4\wave2008_imp4";
joinby h2008 using "H:\Mi unidad\Grant_new\EFF\Imputation5\wave2008_imp5";



save "H:\Mi unidad\Grant_new\wave2008.dta", replace;

erase "H:\Mi unidad\Grant_new\EFF\Imputation1\wave2008_imp1.dta";
erase "H:\Mi unidad\Grant_new\EFF\Imputation2\wave2008_imp2.dta";
erase "H:\Mi unidad\Grant_new\EFF\Imputation3\wave2008_imp3.dta";
erase "H:\Mi unidad\Grant_new\EFF\Imputation4\wave2008_imp4.dta";
erase "H:\Mi unidad\Grant_new\EFF\Imputation5\wave2008_imp5.dta";

*************************************************************************;
************************************* 2011 ******************************;
*************************************************************************;

foreach x in 1 2 3 4 5{; 


cd "H:\Mi unidad\Grant_new\EFF\Imputation`x'";

use seccion6_2011_imp`x'.dta, clear;

joinby h_2011 using otras_secciones_2011_imp`x'.dta;

gen year=2011;

********************************************************************;
** Annual and monthly consumer price index to be used (base 2010) **;
********************************************************************;

gen acpi=81.06;
replace acpi=88.96 if year==2005;
replace acpi=98.52 if year==2008;
replace acpi=103.20 if year==2011;
replace acpi=107.05 if year==2014;

gen mcpi=82.73 					 /* mean oct02-may03 */;
replace mcpi=91.14 if year==2005 /* mean nov05-may06 */;
replace mcpi=98.10 if year==2008 /* mean nov08-jun09 */;
replace mcpi=104.33 if year==2011 /* mean oct11-apr12 */;
replace mcpi=106.42 if year==2014 /* mean sept14-mar15*/;

********************************************************************;
********************************************************************;
*NET WEALTH AND INCOME;

*1.- FOR THE PERCENTAGE OF HOUSEHOLDS OWNING THAT ASSET;

*REAL ASSETS;

*MAIN RESIDENCE;
*To calculate the percentage of households that own their main residence we use the variable p2_1;

gen np2_1=(p2_1==2 & p2_5>0 & p2_5~=.);

gen owner=0;
replace owner=1 if np2_1==1;

gen renter=0 /*renter or (only 2014) renter with purchase option*/;
replace renter=1 if p2_1==1;

gen freeuse=0;
replace freeuse=1 if p2_1==3;

*OTHER REAL ESTATE PROPERTIES;
*To calculate the percentage of households that own other real estate properties we use the variable np2_32; 
gen np2_32=((p2_32==1 & p2_33>=1 & p2_33~=. & p2_39_1>0 & p2_39_1~=.)|
            (p2_32==1 & p2_33>=2 & p2_33~=. & p2_39_2>0 & p2_39_2~=.)|
            (p2_32==1 & p2_33>=3 & p2_33~=. & p2_39_3>0 & p2_39_3~=.)|
            (p2_32==1 & p2_33>3  & p2_33~=. & p2_39_4>0 & p2_39_4~=.));

gen othowner=.;
replace othowner=1 if np2_32==1;
replace othowner=0 if np2_32==0;

*JEWELLERY, WORKS OF ART, ANTIQUES;
*To calculate the percentage of households that own jewellery, works of art and antiques we use the variable np2_82;
gen np2_82=(p2_82==1 & p2_84>0 & p2_84~=.);

gen jewel=.;
replace jewel=0 if np2_82==0;
replace jewel=1 if np2_82==1;


*VALOR DEL NEGOCIO POR TRABAJOS POR CUENTA PROPIA;
*VALUE OF BUSINESSES RELATED TO SELF-EMPLOYMENT;
gen haveneg =(p4_101==1);

gen valhog =0;
replace valhog =valhog + p4_111_1 if p4_101==1 & p4_111_1>0 & p4_111_1~=.;
replace valhog =valhog + p4_111_2 if p4_101==1 & p4_111_2>0 & p4_111_2~=.;
replace valhog =valhog + p4_111_3 if p4_101==1 & p4_111_3>0 & p4_111_3~=.;
replace valhog =valhog + p4_111_4 if p4_101==1 & p4_111_4>0 & p4_111_4~=.;
replace valhog =valhog + p4_111_5 if p4_101==1 & p4_111_5>0 & p4_111_5~=.;
replace valhog =valhog + p4_111_6 if p4_101==1 & p4_111_6>0 & p4_111_6~=.;

gen havenegval =(haveneg==1 & valhog>0);


*ALGUN TIPO DE ACTIVO REAL;
*SOME KIND OF REAL ASSET;

gen  tienereal=(np2_1==1|np2_32==1|np2_82==1| havenegval==1);


*ACTIVOS FINANCIEROS;
*FINANCIAL ASSETS;


*ACCOUNTS AND DEPOSITS USABLE FOR PAYMENTS;
*To calculate the percentage of households that own accounts and deposits usable for payments and that declare a strictly positive value 
*for the balance of those accounts we generate a new variable;

gen np4_5=(p4_5==1 & p4_7_3>0 & p4_7_3~=.);
rename np4_5 account_pay;
label var account_pay "households that own accounts and deposits usable for payments and that declare a strictly positive value";

*LISTED SHARES;
*To calculate the percentage of households that own listed and that declare a strictly positive value for that portfolio we generate a new variable;

gen np4_10=(p4_10==1 & p4_15>0 & p4_15~=.);

rename np4_10 listshare;
label var listshare "household that own listed shares";


*UNLISTED SHARES AND OTHER EQUITY;
*To calculate the percentage of households that own unlisted shares and other equity and that declare a strictly positive
* value for that portfolio we generate a new variable;

gen np4_18=(p4_18==1 & p4_24>0 & p4_24~=.);
rename np4_18 unlistshare;
label var unlistshare "household that own unlisted shares and other equity";


*FIXED-INCOME SECURITIES;
*To calculate the percentage of households that own fixed-income securities and that declare a strictly positive value for that portfolio we generate a new variable;

gen np4_33=(p4_33==1 & p4_35>0 & p4_35~=.);

rename np4_33 fixsec;
label var fixsec "household that own fixed-income securities ";

*MUTUAL FUNDS (FFII);
*To calculate the percentage of households that own mutual funds and that declare a strictly positive value for that portfolio we generate a new variable;

gen np4_27=((p4_27==1 & p4_28>=1 & p4_28~=. & p4_31_1>0 & p4_31_1~=.)|
            (p4_27==1 & p4_28>=2 & p4_28~=. & p4_31_2>0 & p4_31_2~=.)|
            (p4_27==1 & p4_28>=3 & p4_28~=. & p4_31_3>0 & p4_31_3~=.)|
            (p4_27==1 & p4_28>=4 & p4_28~=. & p4_31_4>0 & p4_31_4~=.)|
            (p4_27==1 & p4_28>=5 & p4_28~=. & p4_31_5>0 & p4_31_5~=.)|
            (p4_27==1 & p4_28>=6 & p4_28~=. & p4_31_6>0 & p4_31_6~=.)|
            (p4_27==1 & p4_28>=7 & p4_28~=. & p4_31_7>0 & p4_31_7~=.)|
            (p4_27==1 & p4_28>=8 & p4_28~=. & p4_31_8>0 & p4_31_8~=.)|
            (p4_27==1 & p4_28>=9 & p4_28~=. & p4_31_9>0 & p4_31_9~=.)|
            (p4_27==1 & p4_28>9 & p4_28~=. & p4_31_10>0 & p4_31_10~=.));

rename np4_27 mutfunds;
label var mutfunds "household that own mutual funds";

*CUENTAS VIVIENDA Y CUENTAS NO UTILIZABLES PARA REALIZAR PAGOS;
*Para calcular la proporción de hogares que poseen cuentas y depósitos no utilizables para realizar pagos generamos una nueva variable cuentas;

*HOUSE-PURCHASE SAVINGS ACCOUNTS AND ACCOUNTS NOT USABLE FOR PAYMENTS;
*To calculate the percentage of households that own house-purchase saving accounts and/or accounts not usable for payments and 
*that declare a strictly positive value for the balance of those accounts we generate a new variable;

gen cuentas=((p4_3==1 & p4_7_1>0 & p4_7_1~=.)|(p4_4==1 & p4_7_2>0 & p4_7_2~=.));

rename cuentas account_nopay;
label var account_nopay "household that own accounts and deposits not usable for payments";


*PENSION SCHEMES (plan pensiones);
*To calculate the percentage of households that own pension schemes and that declare a strictly positive value for the balance of those pension schemes we generate a new variable;

gen np5_1=((p5_1==1 & p5_1a>=1 & p5_1a~=. & p5_7_1>0 & p5_7_1~=.)|
           (p5_1==1 & p5_1a>=2 & p5_1a~=. & p5_7_2>0 & p5_7_2~=.)|
           (p5_1==1 & p5_1a>=3 & p5_1a~=. & p5_7_3>0 & p5_7_3~=.)|
           (p5_1==1 & p5_1a>=4 & p5_1a~=. & p5_7_4>0 & p5_7_4~=.)|
           (p5_1==1 & p5_1a>=5 & p5_1a~=. & p5_7_5>0 & p5_7_5~=.)|
           (p5_1==1 & p5_1a>=6 & p5_1a~=. & p5_7_6>0 & p5_7_6~=.)|
           (p5_1==1 & p5_1a>=7 & p5_1a~=. & p5_7_7>0 & p5_7_7~=.)|
           (p5_1==1 & p5_1a>=8 & p5_1a~=. & p5_7_8>0 & p5_7_8~=.)|
           (p5_1==1 & p5_1a>=9 & p5_1a~=. & p5_7_9>0 & p5_7_9~=.)|
           (p5_1==1 & p5_1a>9 & p5_1a~=. & p5_7_10>0 & p5_7_10~=.));

rename np5_1 penplan;
label var penplan "household that own pension schemes";
*SEGUROS DE VIDA;
*Para calcular la proporción de hogares que tienen seguros tipo unit linked o mixto generamos una nueva variable;

*To calculate the percentage of households that own unit-linked or mixed life insurance we generate a new variable;

gen seguro=((p5_9a==1 & p5_10a>=1 & p5_10a~=. & p5_13_1==2 & p5_14_1>0 & p5_14_1~=.)|
                    (p5_9a==1 & p5_10a>=2 & p5_10a~=. & p5_13_2==2 & p5_14_2>0 & p5_14_2~=.)|
                    (p5_9a==1 & p5_10a>=3 & p5_10a~=. & p5_13_3==2 & p5_14_3>0 & p5_14_3~=.)|
                    (p5_9a==1 & p5_10a>=4 & p5_10a~=. & p5_13_4==2 & p5_14_4>0 & p5_14_4~=.)|
                    (p5_9a==1 & p5_10a>=5 & p5_10a~=. & p5_13_5==2 & p5_14_5>0 & p5_14_5~=.)|
                    (p5_9a==1 & p5_10a>5 &   p5_10a~=. & p5_13_6==2 & p5_14_6>0 & p5_14_6~=.)|
	       (p5_9a==1 & p5_10a>=1 & p5_10a~=. & p5_13_1==3 & p5_14_1>0 & p5_14_1~=.)|
                    (p5_9a==1 & p5_10a>=2 & p5_10a~=. & p5_13_2==3 & p5_14_2>0 & p5_14_2~=.)|
                    (p5_9a==1 & p5_10a>=3 & p5_10a~=. & p5_13_3==3 & p5_14_3>0 & p5_14_3~=.)|
                    (p5_9a==1 & p5_10a>=4 & p5_10a~=. & p5_13_4==3 & p5_14_4>0 & p5_14_4~=.)|
                    (p5_9a==1 & p5_10a>=5 & p5_10a~=. & p5_13_5==3 & p5_14_5>0 & p5_14_5~=.)|
                    (p5_9a==1 & p5_10a>5 &   p5_10a~=. & p5_13_6==3 & p5_14_6>0 & p5_14_6~=.));
	

rename seguro lifeinsur;
label var lifeinsur "household that own unit-linked or mixed life insurance";

*PLANES DE PENSIONES INCLUYENDO SEGUROS DE VIDA DE INVERSION O MIXTOS;
*PENSION SCHEMES INCLUDING UNIT-LINKED OR MIXED LIFE INSURANCE;

gen penseg=(penplan==1|lifeinsur==1);

*PORTFOLIOS UNDER MANAGEMENT (carteras gestionadas);

gen cart_gest=((p4_41==1 & p4_42==1) & p4_43>0 & p4_43~=.);


*OTHER FINANCIAL ASSETS; 

*To calculate the percentage of households to whom the business or other people owe money we generate the variable sideuda; 


*PROGRAMA PARA CALCULAR LO QUE LES DEBEN LOS NEGOCIOS A LOS DISTINTOS MIEMBROS DEL HOGAR (P4_116);
*PROGRAM TO OBTAIN WHAT THE BUSINESSES OWE TO THE DIFFERENT HOUSEHOLD MEMBERS (P4_116);

gen valdeuhog=0;
gen havedeuhog=0;
forvalues m=1/6   {;
	replace valdeuhog=valdeuhog+p4_116_`m' if (p4_116_`m'>0 & p4_116_`m'~=.);
	replace havedeuhog=1 if (p4_115_`m'==1);
	};
gen sideuda=((havedeuhog ==1 & valdeuhog>0)|(p4_37==1 & p4_38>0 & p4_38~=.));

rename sideuda creditor;
label var creditor "household to whom the business or other people owe money";

*ALGUN TIPO DE ACTIVO FINANCIERO;
*SOME TYPE OF FINANCIAL ASSET;

gen tienefin=(account_pay==1|listshare==1|unlistshare==1|fixsec==1|mutfunds==1|account_nopay==1|penplan==1|lifeinsur==1|creditor==1|cart_gest==1);

*ALGUN TIPO DE ACTIVO;
*SOME TYPE OF ASSET;

gen tiene=(tienereal==1|tienefin==1);
rename tiene anyasset;




*2.- PARA EL VALOR DE DICHOS ACTIVOS;
*2.- FOR THE VALUE OF THOSE ASSETS;

*ACTIVOS REALES;
*REAL ASSETS;

*MAIN RESIDENCE;
*To obtain the value of the main residence we use the variable p2_5;
gen np2_5=p2_5 if p2_1b==1;
replace np2_5=p2_5*(p2_1c/100) if p2_1b==2;

rename np2_5 vmresid;
label var vmresid "value of the main residence";

*OTHER REAL ESTATE PROPERTIES;
*To obtain the value of the other real estate properties we generate a new variable;

gen otraspr=0;
replace otraspr=otraspr+p2_39_1*(p2_37_1/100) if (p2_33>=1 & p2_33~=. & p2_39_1>=0 & p2_39_1~=. & p2_37_1>0 & p2_37_1~=.);
replace otraspr=otraspr+p2_39_2 *(p2_37_2/100) if (p2_33>=2 & p2_33~=. & p2_39_2>=0 & p2_39_2~=. & p2_37_2>0 & p2_37_2~=.);
replace otraspr=otraspr+p2_39_3* (p2_37_3/100) if (p2_33>=3 & p2_33~=. & p2_39_3>=0 & p2_39_3~=. & p2_37_3>0 & p2_37_3~=.);
replace otraspr=otraspr+p2_39_4 if (p2_33>3 & p2_33~=. & p2_39_4>=0 & p2_39_4~=.);

rename otraspr vothprop;
label var vothprop "value of the other real estate properties";


*JEWELLERY, WORKS OF ART, ANTIQUES;
*To obtain the value of the jewellery, works of art and antiques we use the variable p2_84;
rename p2_84 vjewel;
label var vjewel "value of the jewellery, works of art and antiques";

*VALOR DEL NEGOCIO POR TRABAJOS POR CUENTA PROPIA;
*la mediana del valor del negocio será la mediana de valhog if havenegval==1; 

*TBD;

*VALUE OF THE BUSINESS RELATED TO SELF-EMPLOYMENT;
*The median of the business value is equal to the median of valhog if havenegval==1;


*ACTIVOS FINANCIEROS;
*FINANCIAL ASSETS;

*CUENTAS Y DEPOSITOS UTILIZABLES PARA REALIZAR PAGOS;
*Para calcular el saldo de las cuentas y depósitos para realizar pagos utilizamos la variable p4_7_3;


*ACCOUNTS AND DEPOSITS USABLE FOR PAYMENTS;
*To obtain the balance of the accounts and deposits usable for payments we use the variable p4_7_3;
rename p4_7_3 vaccount_pay;



*ACCIONES COTIZADAS EN BOLSA;
*Para calcular el valor de las acciones cotizadas utilizamos la variable p4_15;


*LISTED SHARES;
*To obtain the value of the listed shares we use the variable p4_15;
rename p4_15 vlistshare;

*ACCIONES NO COTIZADAS EN BOLSA Y PARTICIPACIONES;
*Para calcular el valor de las acciones no cotizadas y participaciones utilizamos la variable p4_24;

*UNLISTED SHARES ANDOTHER EQUITY;
*To obtain the value of the unlisted shares and other equity we use the variable p4_24;
rename p4_24 vunlist;

*VALORES DE RENTA FIJA;
*Para calcular el valor de los valores de renta fija utilizamos la variable p4_35;

*FIXED-INCOME SECURITIES;
*To obtain the value of the fixed-income securities we use the variable p4_35;

rename p4_35 vfixsec;

*FONDOS DE INVERSION;
*Para calcular el valor total de los fondos de inversión utilizamos la variable allf calculada como (i) la suma de los valores de cada uno de los fondos 
*de inversión que posee el hogar (p4_31_i, i=1,…,10) si el número de estos fondos es menor o igual a 10, y (ii) el valor total de los fondos de inversión 
*del hogar si posee más de 10 fondos (p4_28a);

*MUTUAL FUNDS;
*To obtain the total value of mutual funds we use the variable allf calculated as (i) the addition of the values of each mutual fund that the household
* owns (p4_31_i, i=1,…,10) if the number of these funds is 10 or less, and (ii) the household mutual funds’ total value if this one owns more than 10 (p4_28a);

egen allf=rowtotal(p4_31*);
replace allf=p4_28a if p4_28>10;
label var allf "Total value of mutual funds";


*CUENTAS VIVIENDA Y CUENTAS NO UTILIZABLES PARA REALIZAR PAGOS;
*Para calcular el saldo de las cuentas y depósitos no utilizables para realizar pagos generamos una nueva variable;

*HOME-PURCHASE SAVINGS ACCOUNTS AND ACCOUNTS NOT USABLE FOR PAYMENTS;
*To obtain the balance of the accounts and deposits not usable for payments we generate a new variable;  

gen salcuentas=0;
replace salcuentas = salcuentas +p4_7_1 if p4_3==1;
replace salcuentas = salcuentas + p4_7_2 if p4_4==1;

rename salcuentas vaccount_nopay;
label var vaccount_nopay "balance of the accounts and deposits not usable for payments";

*PLANES DE PENSIONES;
*Para calcular valor actualizado de los planes de pensiones generamos una nueva variable;

*PENSION SCHEMES;
*To obtain the current value of the pension schemes we generate a new variable;

gen valor=0; 
replace valor = valor +p5_7_1 if (p5_1==1 & p5_7_1>=0 & p5_7_1~=. );
replace valor = valor + p5_7_2 if (p5_1==1 & p5_7_2>=0 & p5_7_2~=.);
replace valor = valor + p5_7_3 if (p5_1==1 & p5_7_3>=0 & p5_7_3~=.);
replace valor = valor + p5_7_4 if (p5_1==1 & p5_7_4>=0 & p5_7_4~=.);
replace valor = valor + p5_7_5 if (p5_1==1 & p5_7_5>=0 & p5_7_5~=.);
replace valor = valor + p5_7_6 if (p5_1==1 & p5_7_6>=0 & p5_7_6~=.);
replace valor = valor + p5_7_7 if (p5_1==1 & p5_7_7>=0 & p5_7_7~=.);
replace valor = valor + p5_7_8 if (p5_1==1 & p5_7_8>=0 & p5_7_8~=.);
replace valor = valor + p5_7_9 if (p5_1==1 & p5_7_9>=0 & p5_7_9~=.);
replace valor = valor + p5_7_10 if (p5_1==1 & p5_7_10>=0 & p5_7_10~=.);


rename valor vpenplan;
label var vpenplan "current value of the pension schemes";

*No consideramos las mutualidades;
*We do not consider mutual insurance;

*SEGUROS DE VIDA;
*Para calcular el valor de estos seguros tipo unit linked o mixto generamos una nueva variable;

*LIFE INSURANCE;
*To obtain the value of the unit-linked or mixed life insurance we generate a new variable;


gen valseg=0;
replace valseg = valseg +p5_14_1 if ((p5_13_1==2| p5_13_1==3) & p5_14_1>=0 & p5_14_1~=.);
replace valseg = valseg +p5_14_2 if ((p5_13_2==2| p5_13_2==3) & p5_14_2>=0 & p5_14_2~=.);
replace valseg = valseg +p5_14_3 if ((p5_13_3==2| p5_13_3==3) & p5_14_3>=0 & p5_14_3~=.);
replace valseg = valseg +p5_14_4 if ((p5_13_4==2| p5_13_4==3) & p5_14_4>=0 & p5_14_4~=.);
replace valseg = valseg +p5_14_5 if ((p5_13_5==2| p5_13_5==3) & p5_14_5>=0 & p5_14_5~=.);
replace valseg = valseg +p5_14_6 if ((p5_13_6==2| p5_13_6==3) & p5_14_6>=0 & p5_14_6~=.);


rename valseg vlifeinsur;
label var vlifeinsur "value of the unit-linked or mixed life insurance";

*PLANES DE PENSIONES INCLUYENDO SEGUROS DE VIDA DE INVERSION O MIXTOS;
*PENSION SCHEMES INCLUDING UNIT-LINKED OR MIXED LIFE INSURANCE;

gen valpenseg=vpenplan+vlifeinsur;
rename valpenseg vpeninsur;
label var vpeninsur "value of pension schemes plus unit-linked or mixed life insurance";

*OTROS ACTIVOS FINANCIEROS;
*Para calcular el valor de la mediana de lo que se debe al hogar, utilizamos las variables valdeuhog y p4_38 y generamos una nueva variable;

*OTHER FINANCIAL ASSETS;
*To obtain the median of how much is owed to the household, we use the variables valdeuhog and p4_38 and generate a new variable; 

gen odeuhog=0;

replace odeuhog = odeuhog +valdeuhog if (valdeuhog>0);
replace odeuhog = odeuhog +p4_38 if (p4_38>0 & p4_38~=.);

rename odeuhog vcreditor;
label var vcreditor "how much is owed to the household";

*CUADRO 7: PROPORCION DE HOGARES Y MEDIANA DEL VALOR DE LOS DISTINTOS TIPOS DE DEUDA PENDIENTES;
*TABLE 7: PERCENTAGE OF HOUSEHOLDS AND VALUE’S MEDIAN OF THE DIFFERENT TYPES OF OUTSTANDING DEBT;

*DEUDAS  CLASIFICADAS POR TIPO DE ACTIVO INMOBILIARIO (TODO TIPO DE PRESTAMOS);
*DEBT CLASSIFIED BY TYPE OF REAL ESTATE ASSET (ALL KIND OF LOANS);

*VIVIENDA PRINCIPAL;
*MAIN RESIDENCE;

*Para calcular la proporción de hogares que tienen deudas pendientes de préstamos solicitados para la adquisición de la vivienda principal, utilizamos p2_8;
*To obtain the percentage of households that have outstanding debt from loans used to purchase their main residence, we generate a new variable;

gen np2_8=p2_8;
replace np2_8=0 if p2_8==.;

rename np2_8 debtmresid;
label var debtmresid "have outstanding debt from loans used to purchase main residence";

*Para calcular el valor de las deudas pendientes de préstamos solicitados para la adquisición de la vivienda principal, generamos una nueva variable;
*To obtain the value of the outstanding debts from loans used to purchase their main residence, we generate a new variable;

gen dvivpral=0;

replace dvivpral= dvivpral +p2_12_1 if  (p2_8a>=1 & p2_8a~=. & p2_12_1>0 & p2_12_1~=.);

replace dvivpral= dvivpral + p2_12_2 if (p2_8a>=2 & p2_8a~=. &  p2_12_2>0 & p2_12_2~=.);

replace dvivpral= dvivpral +p2_12_3  if (p2_8a>=3 & p2_8a~=. & p2_12_3>0 & p2_12_3~=.);

replace dvivpral= dvivpral +p2_12_4  if (p2_8a>3 & p2_8a~=. & p2_12_4>0 & p2_12_4~=.);

rename dvivpral vdebtmresid;
label var vdebtmresid "value of outstanding debts from loans used to purchase main residence";

*OTRAS PROPIEDADES INMOBILIARIAS DIFERENTES DE LA VIVIENDA PRINCIPAL;
*OTHER REAL ESTATE PROPERTIES DIFFERENT FROM THE MAIN RESIDENCE;

*Para calcular la proporción de hogares que tienen deudas pendientes de préstamos solicitados para la adquisición de otras propiedades inmobiliarias diferentes de la vivienda principal, generamos una nueva variable;

*To obtain the percentage of households that have outstanding debts from loans used to purchase other real estate properties different from the main 
*residence, we generate a new variable;

gen dpdte=(p2_50_1==1|p2_50_2==1|p2_50_3==1|p2_50_4==1);
rename dpdte debtothprop;
label var debtothprop "have outstanding debts from loans used to purchase other real estate properties";

*Para calcular el valor de las deudas pendientes de préstamos solicitados para la adquisición de otras propiedades inmobiliarias diferentes de la vivienda principal, generamos cuatro nuevas variables;

*To obtain the value of the outstanding debts from loans used to purchase other real estate properties different from the main residence, we generate
* four new variables;

*PARA LA PRIMERA PROPIEDAD INMOBILIARIA;
*FOR THE FIRST REAL ESTATE PROPERTY;

gen dprop1=0;

replace dprop1= dprop1+p2_55_1_1 if (p2_51_1>=1 & p2_51_1~=.  &  p2_55_1_1>0 & p2_55_1_1~=.);

replace dprop1= dprop1+ p2_55_1_2 if (p2_51_1>=2 & p2_51_1~=.  & p2_55_1_2>0 & p2_55_1_2~=.);

replace dprop1= dprop1+p2_55_1_3  if (p2_51_1>=3 & p2_51_1~=.  & p2_55_1_3>0 & p2_55_1_3~=.);


*PARA LA SEGUNDA PROPIEDAD INMOBILIARIA;
*FOR THE SECOND REAL ESTATE PROPERTY;

gen dprop2=0;

replace dprop2= dprop2+p2_55_2_1 if (p2_51_2>=1 & p2_51_2~=. & p2_55_2_1>0 & p2_55_2_1~=.);

replace dprop2= dprop2+ p2_55_2_2 if (p2_51_2>=2 & p2_51_2~=. & p2_55_2_2>0 & p2_55_2_2~=.);

replace dprop2= dprop2+ p2_55_2_3  if (p2_51_2>=3 & p2_51_2~=. & p2_55_2_3>0 & p2_55_2_3~=.);


*PARA LA TERCERA PROPIEDAD INMOBILIARIA;
*FOR THE THIRD REAL ESTATE PROPERTY;

gen dprop3=0;

replace dprop3= dprop3+p2_55_3_1 if (p2_51_3>=1 & p2_51_3~=. & p2_55_3_1>0 & p2_55_3_1~=.);

replace dprop3= dprop3+ p2_55_3_2 if (p2_51_3>=2 & p2_51_3~=. & p2_55_3_2>0 & p2_55_3_2~=.);

replace dprop3= dprop3+ p2_55_3_3  if (p2_51_3>=3 & p2_51_3~=. & p2_55_3_3>0 & p2_55_3_3~=.);


*PARA EL RESTO DE PROPIEDADES INMOBILIARIAS CUANDO HAY MAS DE TRES;
*FOR THE REST OF REAL ESTATE PROPERTIES WHEN THESE ARE MORE THAN THREE;

gen dprop4=0;

replace dprop4= dprop4+p2_55_4 if (p2_55_4>0 & p2_55_4~=.);

forvalues i=1(1)4{;
rename dprop`i' vdebtprop`i';
};

label var vdebtprop1 "value of the outstanding debts from loans used to purchase other real estate property #1";
label var vdebtprop2 "value of the outstanding debts from loans used to purchase other real estate property #2";
label var vdebtprop3 "value of the outstanding debts from loans used to purchase other real estate property #3";
label var vdebtprop4 "value of the outstanding debts from loans used to purchase other real estate properties #4";


*CONSIDERANDO CONJUNTAMENTE TODAS LAS PROPIEDADES INMOBILIARIAS DIFERENTES DE LA VIVIENDA PRINCIPAL;
*CONSIDERING ALL REAL ESTATE PROPERTIES DIFFERENT FROM THE MAIN RESIDENCE;

gen deuoprop= vdebtprop1+ vdebtprop2+ vdebtprop3+ vdebtprop4 ; 
rename deuoprop vdebtothprop;
label var vdebtothprop "value of the outstanding debts from loans used to purchase other real estate properties";

*DEUDAS PENDIENTES DE PRESTAMOS SOLICITADOS PARA LA ADQUISICION DE LA VIVIENDA PRINCIPAL CON GARANTIA HIPOTECARIA;
*OUTSTANDING DEBTS FROM LOANS WITH MORTGAGE GUARANTEE USED FOR THE PURCHASE OF THE MAIN RESIDENCE;

*Para calcular la proporción de hogares que tienen deudas pendientes de préstamos CON garantía hipotecaria solicitados para la adquisición de la vivienda principal, generamos una nueva variable;
*To obtain the percentage of households that have outstanding debts from loans with mortgage guarantee used for the purchase of the main residence, 
* we generate a new variable;

gen dpdtehipo = (p2_9_1==1|p2_9_2==1|p2_9_3==1|p2_9_4==1);
rename dpdtehipo mortgmresid;
label var mortgmresid " have mortgage for the purchase of the main residence";

*Para calcular el valor de las deudas pendientes de préstamos CON garantía hipotecaria solicitados para la adquisición de la vivienda principal, generamos una nueva variable;
*To obtain the value of the outstanding debts from loans with mortgage guarantee used for the purchase of the main residence, we generate a new variable;

gen deuhipv =0;

replace deuhipv= deuhipv + p2_12_1 if (p2_8a>=1 & p2_8a~=. & p2_9_1==1 & p2_12_1>0 & p2_12_1~=.);

replace deuhipv = deuhipv + p2_12_2 if (p2_8a>=2 & p2_8a~=. & p2_9_2==1 &  p2_12_2>0 & p2_12_2~=.);

replace deuhipv= deuhipv +p2_12_3  if (p2_8a>=3 & p2_8a~=. & p2_9_3==1 &  p2_12_3>0 & p2_12_3~=.);

replace deuhipv= deuhipv +p2_12_4  if (p2_8a>3 & p2_8a~=. & p2_8a~=. & p2_9_4==1 &  p2_12_4>0 & p2_12_4~=.);

rename deuhipv vmortgmresid;
label var vmortgmresid "value of outstanding mortgages for the purchase of the main residence";


*OTRAS DEUDAS PENDIENTES NO ASOCIADAS A LA ADQUISICION DE ACTIVOS INMOBILIARIOS;
*OTHER OUTSTANDING DEBT NOT RELATED TO THE PURCHASE OF REAL ESTATE ASSETS;

*DEUDAS PENDIENTES DE PRESTAMOS HIPOTECARIOS Y OTROS PRESTAMOS CON GARANTIA REAL;
*OUTSTANDING DEBTS FROM MORTGAGES AND OTHER SECURED LOANS);

*Para calcular la proporción de hogares que tienen deudas pendientes por prestamos hipotecarios y otros préstamos con garantía real generamos una nueva variable;
*To obtain the percentage of households that have outstanding debts from mortgages and other secured loans we generate a new variable;

gen hipo=(p3_2_1==1| p3_2_2==1| p3_2_3==1| p3_2_4==1|p3_2_5==1| p3_2_6==1| p3_2_7==1| p3_2_8==1|
p3_2_1==2| p3_2_2==2| p3_2_3==2| p3_2_4==2|p3_2_4==2|p3_2_5==2| p3_2_6==2| p3_2_7==2| p3_2_8==2|
p3_2_1==10| p3_2_2==10| p3_2_3==10| p3_2_4==10|p3_2_5==10| p3_2_6==10| p3_2_7==10| p3_2_8==10);


rename hipo mortgoth;
label var mortgoth "have mortgage for other porpuses";

*Para calcular el valor de las deudas pendientes por prestamos hipotecarios y otros préstamos con garantía real generamos una nueva variable;
*To obtain the value of the outstanding debts from mortgages and other loans with real guarantee we generate a new variable;

gen phipo=0;

replace phipo = phipo +p3_6_1 if ((p3_2_1==1|p3_2_1==2) & p3_6_1>0 & p3_6_1~=.);

replace phipo = phipo +p3_6_2 if ((p3_2_2==1| p3_2_2==2) & p3_6_2>0 & p3_6_2~=.);

replace phipo = phipo +p3_6_3 if ((p3_2_3==1| p3_2_3==2)  & p3_6_3>0 & p3_6_3~=.);

replace phipo = phipo +p3_6_4 if ((p3_2_4==1| p3_2_4==2) & p3_6_4>0 & p3_6_4~=.);

replace phipo = phipo +p3_6_5 if ((p3_2_5==1| p3_2_5==2) & p3_6_5>0 & p3_6_5~=.);

replace phipo = phipo +p3_6_6 if ((p3_2_6==1| p3_2_6==2) & p3_6_6>0 & p3_6_6~=.);

replace phipo = phipo +p3_6_7 if ((p3_2_7==1| p3_2_7==2) & p3_6_7>0 & p3_6_7~=.);

replace phipo = phipo +p3_6_8 if ((p3_2_8==1| p3_2_8==2) & p3_6_8>0 & p3_6_8~=.);

rename phipo vmortgoth;
label var vmortgoth "value of outstanding mortgages for other purposes";

*Variable capturing any kind of mortgage or secure debt ;
gen mortgage =0;
replace mortgage=1 if mortgoth==1 | mortgmresid==1;

*DEUDAS PENDIENTES DE PRESTAMOS PERSONALES;
*OUTSTANDING DEBTS FROM PERSONAL LOANS;

*Para calcular la proporción de hogares que tienen deudas pendientes por prestamos personales generamos una nueva variable;
*To obtain the percentage of households that have outstanding debts from personal loans we generate a new variable;

gen perso=(p3_2_1==3| p3_2_2==3| p3_2_3==3| p3_2_4==3|p3_2_5==3| p3_2_6==3| p3_2_7==3| p3_2_8==3);
rename perso personal;
label var personal "have outstanding debts from personal loans";

*Para calcular el valor de las deudas pendientes por prestamos personales generamos una nueva variable;
*To obtain the value of the outstanding debts from personal loans we generate a new variable;

gen pperso=0;

replace pperso = pperso +p3_6_1 if (p3_2_1==3 & p3_6_1>0 & p3_6_1~=.);
replace pperso = pperso +p3_6_2 if (p3_2_2==3 & p3_6_2>0 & p3_6_2~=.);
replace pperso = pperso +p3_6_3 if (p3_2_3==3 & p3_6_3>0 & p3_6_3~=.);
replace pperso = pperso +p3_6_4 if (p3_2_4==3 & p3_6_4>0 & p3_6_4~=.);
replace pperso = pperso +p3_6_5 if (p3_2_5==3 & p3_6_5>0 & p3_6_5~=.);
replace pperso = pperso +p3_6_6 if (p3_2_6==3 & p3_6_6>0 & p3_6_6~=.);
replace pperso = pperso +p3_6_7 if (p3_2_7==3 & p3_6_7>0 & p3_6_7~=.);
replace pperso = pperso +p3_6_8 if (p3_2_8==3 & p3_6_8>0 & p3_6_8~=.);

rename pperso vpersonal;
label var vpersonal "value of personal loans";


*DEUDAS PENDIENTES CON TARJETAS DE CREDITO;
*OUTSTANDING CREDIT CARD BALANCES;

*Para calcular la proporción de hogares que tienen deudas pendientes con tarjetas de credito generamos una nueva variable;
*To obtain the percentage of households that have outstanding credit card balances we generate a new variable;

gen deuda_tarj=(p8_5a>0 & p8_5a~=.);
rename deuda_tarj credcard;
label var credcard "have outstanding credit card balances";

*Para calcular el valor de las deudas pendientes con tarjetas de credito generamos una nueva variable;
*To obtain the value of outstanding credit card balances we generate a new variable;

gen ptmos_tarj=0;

replace ptmos_tarj= p8_5a if (p8_5a>0 & p8_5a~=.);
rename ptmos_tarj vcredcard;
label var vcredcard "value of outstanding credit card balances";



*OTRAS DEUDAS;
*OTHER DEBTS;

*Para calcular la proporción de hogares que tienen otras deudas pendientes generamos una nueva variable;
*To obtain the percentage of households that have other outstanding debts we generate a new variable;

gen otrasd=(p3_2_1==4| p3_2_2==4| p3_2_3==4| p3_2_4==4| p3_2_5==4| p3_2_6==4| p3_2_7==4| p3_2_8==4|p3_2_1==5| p3_2_2==5| p3_2_3==5| p3_2_4==5| p3_2_5==5|
 p3_2_6==5| p3_2_7==5| p3_2_8==5| p3_2_1==6| p3_2_2==6| p3_2_3==6| p3_2_4==6| p3_2_5==6| p3_2_6==6| p3_2_7==6| p3_2_8==6| p3_2_1==7| p3_2_2==7| p3_2_3==7|
 p3_2_4==7| p3_2_5==7| p3_2_6==7| p3_2_7==7| p3_2_8==7| p3_2_1==8| p3_2_2==8| p3_2_3==8| p3_2_4==8| p3_2_5==8| p3_2_6==8| p3_2_7==8| p3_2_8==8| p3_2_1==9|
 p3_2_2==9| p3_2_3==9| p3_2_4==9| p3_2_5==9| p3_2_6==9| p3_2_7==9| p3_2_8==9| p3_2_1==97| p3_2_2==97| p3_2_3==97| p3_2_4==97 | p3_2_5==97| p3_2_6==97| 
 p3_2_7==97| p3_2_8==97);
rename otrasd othdebt;
label var othdebt "households that have other outstanding debt";


*Para calcular el valor de las otras deudas pendientes generamos una nueva variable;
*To obtain the value of the other outstanding debts we generate a new variable;

gen potrasd =0;

replace potrasd = potrasd +p3_6_1 if ((p3_2_1==4| p3_2_1==5| p3_2_1==6| p3_2_1==7| p3_2_1==8|p3_2_1==9|
p3_2_1==97) & p3_6_1>0 & p3_6_1~=.);
replace potrasd = potrasd +p3_6_2 if ((p3_2_2==4| p3_2_2==5|  p3_2_2==6| p3_2_2==7| p3_2_2==8|p3_2_2==9|
p3_2_2==97) & p3_6_2>0 & p3_6_2~=.);
replace potrasd = potrasd +p3_6_3 if ((p3_2_3==4| p3_2_3==5| p3_2_3==6| p3_2_3==7| p3_2_3==8|p3_2_3==9|
p3_2_3==97) & p3_6_3>0 & p3_6_3~=.);
replace potrasd = potrasd +p3_6_4 if ((p3_2_4==4| p3_2_4==5| p3_2_4==6| p3_2_4==7| p3_2_4==8|p3_2_4==9|
p3_2_4==97) & p3_6_4>0 & p3_6_4~=.);
replace potrasd = potrasd +p3_6_5 if ((p3_2_5==4| p3_2_5==5| p3_2_5==6| p3_2_5==7| p3_2_5==8|p3_2_5==9|
p3_2_5==97) & p3_6_5>0 & p3_6_5~=.);
replace potrasd = potrasd +p3_6_6 if ((p3_2_6==4| p3_2_6==5| p3_2_6==6| p3_2_6==7| p3_2_6==8|p3_2_6==9|
p3_2_6==97) & p3_6_6>0 & p3_6_6~=.);
replace potrasd = potrasd +p3_6_7 if ((p3_2_7==4| p3_2_7==5| p3_2_7==6| p3_2_7==7| p3_2_7==8|p3_2_7==9|
p3_2_7==97) & p3_6_7>0 & p3_6_7~=.);
replace potrasd = potrasd +p3_6_8 if ((p3_2_8==4| p3_2_8==5| p3_2_8==6| p3_2_8==7| p3_2_8==8|p3_2_8==9|
p3_2_8==97) & p3_6_8>0 & p3_6_8~=.);

rename potrasd vothdebt;
label var vothdebt "value of the other outstanding debts";


******************************************************************************************************;
******************************************************************************************************;

*                          R A N K I N G     A: NATURE OF THE DEBT									 *;

******************************************************************************************************;
******************************************************************************************************;
gen housesec=0;
gen houseunsec=0;
gen othsecured=0;
gen consumer=0;
gen rest=0;

gen vhousesec=0;
gen vhouseunsec=0;
gen vothsecured=0;
gen vconsumer=0;
gen vrest=0;

replace vhousesec=vhousesec+p2_55_4 if p2_55_4!=. /*Consider as secured, all debts attached to fourth real state properties in advanced */;

forvalues i=1(1)4 {;
replace housesec=1 if p2_9_`i'<=2;
replace vhousesec=vhousesec+p2_12_`i' if p2_9_`i'<=2; 
replace houseunsec=1 if p2_9_`i'>2 & p2_9_`i'<=97;
replace vhouseunsec=vhouseunsec+p2_12_`i' if p2_9_`i'>2 & p2_9_`i'<=97;
};

forvalues i=1(1)3 {;
		forvalues s=1(1)3 {; 
		replace housesec=1 if p2_52_`i'_`s'<=2;
		replace vhousesec=vhousesec+p2_55_`i'_`s' if  p2_52_`i'_`s'<=2;
		replace houseunsec=1 if p2_52_`i'_`s'>2 & p2_52_`i'_`s'<=97;
		replace vhouseunsec=vhousesec+p2_55_`i'_`s' if  p2_52_`i'_`s'>2 & p2_52_`i'_`s'<=97;
};
};

forvalues i=1(1)8 {;
replace othsecured=1 if p3_2_`i'<=2;
replace vothsecured=vothsecured+p3_6_`i' if p3_2_`i'<=2;
replace consumer=1 if p3_2_`i'==3;
replace vconsumer=vconsumer+p3_6_`i' if p3_2_`i'==3;
replace rest=1 if p3_2_`i'>3 & p3_2_`i'<=97;
replace vrest=vrest+p3_6_`i' if p3_2_`i'>3 & p3_2_`i'<=97;

};
******************************************************************************************************;
******************************************************************************************************;

*                          R A N K I N G     B: OBJECIVE OF THE DEBT									 *;

******************************************************************************************************;
******************************************************************************************************;

gen housing=0;
*gen carloan=0;
gen busloan=0;
gen restbis=0;

replace housing=1 if housesec==1;
replace restbis=1 if houseunsec==1;
forvalues i=1(1)8 {;
*replace carloan=1 if p3_3_`i'==2;
replace busloan=1 if p3_3_`i'==12;
replace housing=1 if p3_3_`i'==14 & p3_2_`i'<=2;
replace restbis=1 if p3_3_`i'==1 | p3_3_`i'==2 | p3_3_`i'==3 | p3_3_`i'==4 | p3_3_`i'==34 | p3_3_`i'==5 | p3_3_`i'==6 | p3_3_`i'==7 | p3_3_`i'==8 | p3_3_`i'==9 |
						p3_3_`i'==10 | p3_3_`i'==11 | p3_3_`i'==13 | (p3_3_`i'==14 & p3_2_`i'>2) | p3_3_`i'==15 | p3_3_`i'==97;
};

gen vhousing=0;
*gen vcarloan=0;
gen vbusloan=0;
gen vrestbis=0;

replace vhousing=vhousesec;
replace vrestbis=vhouseunsec;
forvalues i=1(1)8 {;
*replace vcarloan=vcarloan + p3_6_`i' if p3_3_`i'==2;
replace vbusloan=vbusloan + p3_6_`i'  if p3_3_`i'==12;
replace vhousing=vhousing + p3_6_`i' if p3_3_`i'==14 & p3_2_`i'<=2;
replace vrestbis=vrestbis + p3_6_`i' if p3_3_`i'==1 | p3_3_`i'==2 | p3_3_`i'==3 | p3_3_`i'==4 | p3_3_`i'==34 | p3_3_`i'==5 | p3_3_`i'==6 | p3_3_`i'==7 | p3_3_`i'==8 | p3_3_`i'==9 |
						p3_3_`i'==10 | p3_3_`i'==11 | p3_3_`i'==13 | (p3_3_`i'==14 & p3_2_`i'>2) | p3_3_`i'==15 | p3_3_`i'==97;;
};

foreach var in vhousing vbusloan vcredcard vrestbis {;
replace `var'=`var'/acpi*100;
};


 ******************* INTEREST RATES *************************;
* Main residence;
forvalues i=1(1)4{;
*rename p2_9_`i' loantypemresid_`i' /* 1-mortgage, 2- othsecured, 3- personal, 4- credit line, 5- deferred, 6- advances, 7- friends family, 97- other, 98- don't know missing */;
rename p2_13_`i' loanratemresid_`i';
rename p2_14_`i' loanfixmresid_`i';
replace loanfixmresid_`i'=1 if loanfixmresid_`i'==22;
replace loanfixmresid_`i'=0 if loanfixmresid_`i'==11;
};

* Other properties (up to 3 additional properties and 3 loans for each one);
forvalues a=1(1)3{ /*property*/;
forvalues i=1(1)3{ /*loan*/;

*rename p2_52_`a'_`i' loantypeothprop_`a'_`i' /* 1-mortgage, 2- othsecured, 3- personal, 4- credit line, 5- deferred, 6- advances, 7- friends family, 97- other, 98- don't know missing */;
rename p2_56_`a'_`i' loanrateothprop_`a'_`i';
rename p2_57_`a'_`i' loanfixothprop_`a'_`i';
replace loanfixothprop_`a'_`i'=1 if loanfixothprop_`a'_`i'==22;
replace loanfixothprop_`a'_`i'=0 if loanfixothprop_`a'_`i'==11;
};
};


* Other loans;
forvalues i=1(1)8{;
*rename p3_2_`i' loantypeother_`i' /* 1-mortgage, 2- othsecured, 3- personal, 4- credit line, 5- deferred, 6- advances, 7- friends family, 97- other, 98- don't know missing */;
rename p3_7_`i' loanrateother_`i';
rename p3_8_`i' loanfixother_`i';
replace loanfixother_`i'=1 if loanfixother_`i'==22;
replace loanfixother_`i'=0 if loanfixother_`i'==11;
};

* Credit card;
rename p8_5c int_credcard;

*************************** INTEREST RATES *******************************;
******* Housing ********;
gen int_housing=0;
forvalues i=1(1)4{;
replace int_housing=int_housing+loanratemresid_`i'*p2_12_`i' if p2_9_`i'<=2; 
};

forvalues a=1(1)3 {;
forvalues i=1(1)3 {;
replace int_housing=int_housing+loanrateothprop_`a'_`i'*p2_55_`a'_`i' if  p2_52_`a'_`i'<=2;
};
};

forvalues i=1(1)8{;
replace int_housing=int_housing+loanrateother_`i'*p3_6_`i' if p3_3_`i'==14 & p3_2_`i'<=2;
};
replace p2_55_4=0 if p2_55_4==.;
replace int_housing=int_housing/(vhousing-p2_55_4);

******** Business *******;
gen int_busloan=0;
forvalues i=1(1)8{;
replace int_busloan=int_busloan+loanrateother_`i'*p3_6_`i' if p3_3_`i'==12;
};

replace int_busloan=int_busloan/vbusloan;

********* Other *********;
gen int_restbis=0;
forvalues i=1(1)4{;
replace int_restbis=int_restbis+loanratemresid_`i'*p2_12_`i' if p2_9_`i'>2 & p2_9_`i'<=97; 
};

forvalues a=1(1)3 {;
forvalues i=1(1)3 {;
replace int_restbis=int_restbis+loanrateothprop_`a'_`i'*p2_55_`a'_`i' if  p2_52_`a'_`i'>2 & p2_52_`a'_`i'<=97;
};
};

forvalues i=1(1)8{;
replace int_restbis=int_restbis+loanrateother_`i'*p3_6_`i'  if p3_3_`i'==1 | p3_3_`i'==2 | p3_3_`i'==3 | p3_3_`i'==4 | p3_3_`i'==34 | p3_3_`i'==5 | p3_3_`i'==6 | p3_3_`i'==7 | p3_3_`i'==8 | p3_3_`i'==9 |
						p3_3_`i'==10 | p3_3_`i'==11 | p3_3_`i'==13 | (p3_3_`i'==14 & p3_2_`i'>2) | p3_3_`i'==15 | p3_3_`i'==97;
};
replace int_restbis=int_restbis/vrestbis;

*************** Debt Portfolio Structure ***************;
/* Housing (debt 1), busloan (portfdebt2), Credcard (debt 3), Rest (debt 4)*/; 


******* ONE DEBT ********************************************************************;
gen portfdebt1=0;
replace portfdebt1=1 if housing==1 & busloan==0 & credcard==0 & restbis==0;

gen portfdebt2=0;
replace portfdebt2=1 if housing==0 & busloan==1 & credcard==0 & restbis==0;

					
gen portfdebt3=0;
replace portfdebt3=1 if housing==0 & busloan==0 & credcard==1 & restbis==0;

gen portfdebt4=0;
replace portfdebt4=1 if housing==0 & busloan==0 & credcard==0 & restbis==1;


******* TWO DEBTS ********************************************************************;
gen portfdebt12=0;
replace portfdebt12=1 if housing==1 & busloan==1 & credcard==0 & restbis==0;

gen portfdebt13=0;
replace portfdebt13=1 if housing==1 & busloan==0 & credcard==1 & restbis==0;

gen portfdebt14=0;
replace portfdebt14=1  if housing==1 & busloan==0 & credcard==0 & restbis==1;

gen portfdebt23=0;
replace portfdebt23=1  if housing==0 & busloan==1 & credcard==1 & restbis==0;

gen portfdebt24=0;
replace portfdebt24=1  if housing==0 & busloan==1 & credcard==0 & restbis==1;


gen portfdebt34=0;
replace portfdebt34=1  if housing==0 & busloan==0 & credcard==1 & restbis==1;


**********THREE DEBTS ********************************************************************;
gen portfdebt123=0;
replace portfdebt123=1  if housing==1 & busloan==1 & credcard==1 & restbis==0;

gen portfdebt124=0;
replace portfdebt124=1  if housing==1 & busloan==1 & credcard==0 & restbis==1;

gen portfdebt134=0;
replace portfdebt134=1  if housing==1 & busloan==0 & credcard==1 & restbis==1;

gen portfdebt234=0;
replace portfdebt234=1  if housing==0 & busloan==1 & credcard==1 & restbis==1;

********* FOUR DEBTS *********************************************************************;
gen portfdebt1234=0;
replace portfdebt1234=1  if housing==1 & busloan==1 & credcard==1 & restbis==1;
******************************************************************************************************;

*ALGUN TIPO DE DEUDA PENDIENTE;
*SOME TYPE OF OUTSTANDING DEBT;

*Para calcular la proporción de hogares que tienen algún tipo de deuda pendiente generamos una nueva variable;
*To obtain the percentage of households that have some type of outstanding debt we generate a new variable;

gen adeuda= (debtmresid==1| debtothprop==1| p3_1>0 | credcard==1);
rename adeuda anydebt;
label var anydebt "have some type of outstanding debt";

*Para calcular el valor de las deudas pendientes generamos una nueva variable;
*To obtain the value of the outstanding debt we generate a new variable;

gen vdeuda= vdebtmresid + vdebtothprop+ vmortgoth+ vpersonal+ vothdebt + vcredcard;
rename vdeuda vdebt;
label var vdebt "value of the outstanding debt";

foreach var in portfdebt1 portfdebt2 portfdebt3 portfdebt4 portfdebt12 portfdebt13 portfdebt14 portfdebt23 
 portfdebt24 portfdebt34 portfdebt123 portfdebt124 portfdebt134 portfdebt234 portfdebt1234 {;
 
 gen v`var'=.;
 replace v`var'=vdebt if `var'==1;
 
 };
 

*VARIABLES DE RIQUEZA TOTAL Y RIQUEZAS INTERMEDIAS;
*TOTAL AND INTERMEDIATE WEALTH VARIABLES;


*ACTIVOS REALES;
*REAL ASSETS;

gen actreales=0;
replace actreales=actreales+vmresid if (vmresid>0 & vmresid~=.);
replace actreales=actreales+vothprop if (vothprop>0 & vothprop~=.);
replace actreales=actreales+vjewel if (vjewel>0 & vjewel~=.);
replace actreales=actreales+valhog if (valhog>0 & valhog~=.);

rename actreales rassets;
label var rassets "Value of real assets";


*ACTIVOS FINANCIEROS;
*FINANCIAL ASSETS;

gen actfinanc=0;
replace actfinanc=actfinanc+vaccount_pay if (vaccount_pay>0 & vaccount_pay~=.);
replace actfinanc=actfinanc+vlistshare if (vlistshare>0 & vlistshare~=.);
replace actfinanc=actfinanc+vunlist if (vunlist>0 & vunlist~=.);
replace actfinanc=actfinanc+vfixsec if (vfixsec>0 & vfixsec~=.);
replace actfinanc=actfinanc+allf if (allf>0 & allf~=.);
replace actfinanc=actfinanc+p4_43 if (p4_43>0 & p4_43~=.);
replace actfinanc=actfinanc+vaccount_nopay if (vaccount_nopay>0 & vaccount_nopay~=.);
replace actfinanc=actfinanc+vpenplan if (vpenplan>0 & vpenplan~=.);
replace actfinanc=actfinanc+vlifeinsur if (vlifeinsur>0 & vlifeinsur~=.);
replace actfinanc=actfinanc+vcreditor if (vcreditor>0 & vcreditor~=.);


rename actfinanc fassets;
label var fassets "Value of financial assets";

*RIQUEZA BRUTA;
*GROSS WEALTH;

gen riquezabr=0;
replace riquezabr=riquezabr+rassets+fassets;

rename riquezabr gwealth;
label var gwealth "Gross Wealth";

*RIQUEZA NETA=RIQUEZA BRUTA-DEUDAS;
*NET WEALTH=GROSS WEALTH-DEBTS;

gen riquezanet=gwealth-vdebt;
rename riquezanet nwealth;
label var nwealth "Net Wealth";

*CUADRO 6: VALOR TIPOS DE DEUDA SEGUN OBJETIVO DE LA DEUDA;
*TABLE 6: VALUE OF DEBTS BY PURPOSE OF DEBTS;

*TBD;

*Para deuda por compra vivienda principal usamos dvivpral;
*For debt originated by home purchase we use dvivpral;

*Para deuda por compra otras prop. inmobiliarias usamos deuoprop;
*For debt originated by purchase of other real estate properties we use deuoprop;

*Para deudas pendientes por el resto de deudas (garantia real, credito personal, otras deudas, deudas con tarjetas de credito) usaremos deuotros;
*For other outstanding debts (secured loans, personal loans, credit card balances and other debts) we use deuotros;

*CUADRO 8: RATIOS INDIVIDUALES DE DEUDA;
*TABLE 8: INDIVIDUAL DEBT RATIOS;

*PAGOS POR DEUDAS;
*DEBT PAYMENTS;

*Para el total de pagos por deudas generamos la variable pagodeuda;
*For total debt payments we generate the variable pagodeuda;

gen pagodeuda=0;
gen pagodeuviv=0;
gen pagodeuoprop=0;
gen pagodeusec3=0;
set output error;
forvalues j=1/4 {;
	display _newline(1) `j';
	gen np2_18_`j'=p2_18_`j';
	replace np2_18_`j'=0 if (p2_18_`j'==.|p2_18_`j'<0);
	replace pagodeuviv=pagodeuviv+np2_18_`j';
			};

forvalues j=1/8 {;
	display _newline(1) `j';
	gen np3_11_`j'=p3_11_`j';
	replace np3_11_`j'=0 if (p3_11_`j'==.|p3_11_`j'<0);
	replace pagodeusec3=pagodeusec3+np3_11_`j';
			};

forvalues m=1/3   {;
	forvalues j=1/3 {;
	display _newline(1) `m' `j';
		gen np2_61_`m'_`j'=p2_61_`m'_`j';
	replace np2_61_`m'_`j'=0 if (p2_61_`m'_`j'==.|p2_61_`m'_`j'<0);
	replace pagodeuoprop=pagodeuoprop+np2_61_`m'_`j';
			};
};
set output proc;

gen np2_61_4=p2_61_4;
replace np2_61_4=0 if (p2_61_4==. | p2_61_4<0);
replace pagodeuoprop=pagodeuoprop+np2_61_4;

gen np8_5b=p8_5b;
replace np8_5b=0 if (p8_5b==. | p8_5b<0);
gen pagotarjeta=np8_5b;
	
replace pagodeuda=pagodeuviv+pagodeuoprop+pagodeusec3 + pagotarjeta;


rename pagodeuda paydebt;
label var paydebt "Monthly total debt payments";
rename pagodeuviv paydresid;
label var paydresid "Monthly residential debt payments";
rename pagodeuoprop payothprop;
label var payothprop "Monthly other properties debt payments";
rename pagodeusec3 paypersonal;
label var paypersonal "Monthly personal debt payments";

*CUADRO 9: GASTO EN BIENES DURADEROS Y NO DURADEROS Y TENENCIA DE BIENES DURADEROS;
*TABLE 9: EXPENDITURE ON NON-DURABLE AND DURABLE GOODS AND HOLDINGS OF DURABLE GOODS;

*1.-GASTO ANUAL BIENES VARIOS (% y mediana);
*1.-ANNUAL EXPENDITURE ON DIFFERENT GOODS (% and median);

*Gasto anual en Alimentacion;
*Annual expenditure on Food;

gen frec=12 if p9_2b==2;
replace frec=12*4.3 if p9_2b==1;
gen alim=0;
replace alim=alim+(p9_2*frec) if p9_2>0;
rename alim food;
label var food "Annual expenditure on Food";

*Gasto anual en Otros bienes no duraderos;
*Annual expenditure on Other non-durable goods;

gen nodur=0;
replace nodur=nodur+ (p9_1*12)-food if p9_1>0;
label var nodur "Annual expenditure on Other non-durable goods";

*Gasto anual en vehiculos (si/no y valor);
*Annual expenditure on vehicles (yes/no and value);

*Para decisión adquisición vehículos;
*For the decision to buy vehicles;

gen gvehic=(p2_73==1 | p2_77==1);
rename gvehic vehic;
label var vehic "household purchased a vehicle that year";

*Para valor adquisicion vehículos;
*For the value of vehicles purchased;

gen gimpvehic=0;
replace gimpvehic=gimpvehic+p2_74 if (p2_74>0 & p2_74~=.);
replace gimpvehic=gimpvehic+p2_78 if (p2_78>0 & p2_78~=.);
rename gimpvehic vvehicle;
label var vvehicle "value of vehicles purchased";

*Gasto anual en Otros bienes duraderos (si/no y valor);
*Annual expenditure on Other durable goods (yes/no and value);


*Para decisión adquisición bienes duraderos utilizamos la p2_69;
*For the decision to buy durable goods we use the variable p2_69;

*Para valor adquisicion bienes duraderos usamos p2_70;
*For the value of durable goods purchases we use p2_70;


*2.- PARA TENENCIA DURADEROS (% Y MEDIANA);
*2.- FOR HOLDINGS OF DURABLE GOODS (% AND MEDIAN);

*Tenencia vehiculos;
*Holding of vehicles;

*Proporcion con vehiculos;
*Percentage with vehicles;

gen tvehic=(p2_72>0|p2_76>0);

*Mediana para los que tienen;
*Median for the ones who have; 

gen timpvehic=0;
replace timpvehic = timpvehic + p2_75 if (p2_72>0 & p2_75>0 & p2_75~=.);
replace timpvehic = timpvehic + p2_79 if ( p2_76>0 &  p2_79>0 & p2_79~=.);

*Tenencia Otros bienes duraderos;
*Holding of Other durable goods;

*Para valor tenencia bienes duraderos usamos p2_71;
*For the value of durable goods holdings we use p2_71;


*VARIABLES DE CARACTERISTICAS DE LOS HOGARES QUE FIGURAN EN LOS CUADROS;
*VARIABLES OF HOUSEHOLD CHARACTERISTICS THAT APPEAR IN THE TABLES;

*1.- DEFINICIÓN DE PERCENTILES (i) RENTA TOTAL HOGAR Y (ii) RIQUEZA NETA;
*1.- DEFINITION OF PERCENTILES (i) HOUSEHOLD TOTAL INCOME AND (ii) NET WEALTH; 
rename renthog hhincome /* annual 2001 for 2002 wave, 2004 (2005 wave), 2007 (2008 wave) */;
_pctile hhincome [pweight=facine3], p(20,40,60,80,90);
return list;

gen percrent=1 if (hhincome<r(r1));
replace percrent=2 if (hhincome>=r(r1) & hhincome<r(r2));
replace percrent=3 if (hhincome>=r(r2) & hhincome<r(r3));
replace percrent=4 if (hhincome>=r(r3) & hhincome<r(r4));
replace percrent=5 if (hhincome>=r(r4) & hhincome<r(r5));
replace percrent=6 if  hhincome>=r(r5);


_pctile nwealth [pweight=facine3], p(25,50,75,90);
return list;

gen percriq=1 if (nwealth<r(r1));
replace percriq=2 if (nwealth>=r(r1) & nwealth<r(r2));
replace percriq=3 if (nwealth>=r(r2) & nwealth<r(r3));
replace percriq=4 if (nwealth>=r(r3) & nwealth<r(r4));
replace percriq=5 if  nwealth>=r(r4);

gen percriq25=1 if nwealth==r(r1);
gen percriq50=1 if nwealth==r(r2);
gen percriq75=1 if nwealth==r(r3);

foreach var in vhousing vbusloan vcredcard vrestbis {;
gen nwealth_`var'=nwealth +`var';

gen percriq_`var'25=1 if nwealth_`var'==r(r1);
gen percriq_`var'50=1 if nwealth_`var'==r(r2);
gen percriq_`var'75=1 if nwealth_`var'==r(r3);
};
*2.- NOMBRE Y CODIFICACIÓN DE LAS VARIABLES QUE RECOGEN CARACTERÍSTICAS SOCIO-DEMOGRÁFICAS DEL HOGAR QUE APARECEN EN LOS CUADROS;
*2.- NAME AND CODING OF THE VARIABLES THAT CONTAIN HOUSEHOLDS SOCIO-DEMOGRAPHIC CHARACTERISTICS THAT APPEAR IN THE TABLES;

*EDAD DEL CABEZA DE FAMILIA;
*AGE OF HOUSEHOLD HEAD;
*bage: toma valores 1 a 6, <35, >34 & <45, >44 & <55, >54 & <65, >64 & <75, >74;
*bage: takes values 1 to 6, <35, >34 & <45, >44 & <55, >54 & <65, >64 & <75, >74;

*SITUACION LABORAL DEL CABEZA DE FAMILIA;
*LABOUR MARKET SITUATION OF HOUSEHOLD HEAD;
*nsitlabdom: toma valores 1 a 4, empleado por cuenta ajena, empleado por cuenta propia, jubilado, otro tipo de inactivo o parado;
*nsitlabdom: takes values 1 to 4, employee, self-employed, retired, other type of economic inactivity or unemployed;

*NIVEL DE EDUCACION DEL CABEZA DE FAMILIA;
*LEVEL OF EDUCATION OF HOUSEHOLD HEAD;
*neducdom: toma valores 1 a 3, inferior a bachillerato, bachillerato, estudios universitarios;
*neducdom: takes values 1 to 3, below secondary education, secondary education, University education;

*REGIMEN DE TENENCIA DE LA VIVIENDA PRINCIPAL;
*STATUS OF MAIN RESIDENCE;
*np2_1: toma valores 1 y 0, propiedad, otros regímenes de tenencia;
*np2_1: takes values 1 and 0, ownership, other;


*NUMERO DE ADULTOS EN EL HOGAR TRABAJANDO;
*NUMBER OF ADULT HOUSEHOLD MEMBERS WORKING;
*nnumadtrab: toma valores 0 a 3, ninguno, uno, dos, tres o más;
*nnumadtrab: takes values 0 to 3, none, one, two, three or more;


*NUMERO DE MIEMBROS EN EL HOGAR;
*NUMBER OF HOUSEHOLD MEMBERS;
*np1: toma valores 1 a 5, uno, dos, tres, cuatro, cinco o más.
*np1: takes values 1 to 5, one, two, three, four, five or more.
	

**** Reference person (designed by the household) variables ****;
/* From questionnaire: "The reference person is the person, or one of the persons, responsible for the accommodation. It will normally be the person in the 
household who chiefly deals with the financial issues." */;

rename p1 members /* Number of household members */;



forvalues i = 1(1)9 {;
	rename p1_1_`i' sex`i' /* Male (1), Female (0)*/;
	replace sex`i'=0 if sex`i'==2;
	rename p1_2b_`i' nac`i';
	rename p1_3_`i' relref`i';
	rename p1_5_`i' educ`i' /* Education level (see questionnaire)*/;
	rename p1_7_`i' health`i' /* Health status of reference person: 1-very good, 2-good, 3-acceptable, 4-poor, 5-very poor */;
	rename p6_1c1_`i' employee`i';
	rename p6_1c2_`i' selfemployed`i';
	rename p6_1c3_`i' unemployed`i';
	rename p6_1c4_`i' retiree`i';
	rename p6_1c5_`i' disable`i';
	rename p6_1c6_`i' student`i';
	rename p6_1c7_`i' housew`i';
	rename p6_1c8_`i' oth_inact`i';
	rename p6_4_`i' typejob`i';
	gen bankjob`i'=0;
	replace bankjob`i'=1 if typejob`i'==9;
	};

	
forvalues i = 1(1)9 {;
	gen ageaux`i'=0;
	replace ageaux`i'=2011-nac`i';
	gen child`i'=0;
	replace child`i'=1 if ageaux`i'<16 ;
	};

cap drop ageaux*;

egen nchilds=rowtotal(child1-child9);
	
gen sex=0;
gen nac=0;
gen educ=0;
gen health=0;
gen employee=0;
gen selfemployed=0;
gen unemployed=0;
gen retiree=0;
gen disable=0;
gen student=0;
gen housew=0;
gen oth_inact=0;
gen bankjob=0;

* Dummy variable for university degree;
* Ordinary university degree / Training leading to an officially recognised professional specialisation;
* Postgraduate university education ;

forvalues i = 1(1)9 {;
gen univ`i'=0;
replace univ`i'=1 if educ`i'==10 | educ`i'==11 | educ`i'==12;
};

gen univ=0;

/* Marital status reference person: married if any other person in the household declares to be the couple of the head */;

gen married=0;

forvalues i = 2(1)9 {;
	replace married=1 if relref`i'==2;
	};

gen couplewith=(married==1 & nchilds>0);
gen couplewithout=(married==1 & nchilds==0);
gen singlewith=(married==0 & nchilds>0);
gen singlewithout=(married==0 & nchilds==0);
	
rename p1_4_1 marital1 /* Marital status reference person: 1-single, 2-married, 3-de facto partner 
						4-separated, 5-divorced, 6-widowed */;

/* With the information of the other members, create variables that summarize the familiar characteristics */;

*gen othcoup=0 /* to identify those hh where household head is not the reference person in the survey */;

*CRITERIUM: Take the main earner in employees. Otherwise, take the male;

* Compute wage for each member of the houysehold;
forvalues i=1(1)9{;
replace student`i'=0 if oth_inact`i'==1 | disable`i'==1 | housew`i'==1 | unemployed`i'==1 | retiree`i'==1 | selfemployed`i'==1 | employee`i'==1;
replace oth_inact`i'=0 if disable`i'==1 | housew`i'==1 | unemployed`i'==1 | retiree`i'==1 | selfemployed`i'==1 | employee`i'==1;
replace disable`i'=0 if housew`i'==1 | unemployed`i'==1 | retiree`i'==1 | selfemployed`i'==1 | employee`i'==1;
replace housew`i'=0 if unemployed`i'==1 | retiree`i'==1 | selfemployed`i'==1 | employee`i'==1;
replace unemployed`i'=0 if retiree`i'==1 | selfemployed`i'==1 | employee`i'==1;
replace retiree`i'=0 if selfemployed`i'==1 | employee`i'==1;
replace selfemployed`i'=0 if employee`i'==1;
gen ageaux`i'=0;
replace ageaux`i'=2011-nac`i';
replace retiree`i'=1 if (housew`i'==1 | oth_inact`i'==1 | disable`i'==1 | student`i'==1) & ageaux`i'>=65 /* Take this persons as retired */;
replace housew`i'=0 if retiree`i'==1;
replace oth_inact`i'=0 if retiree`i'==1;
replace disable`i'=0 if retiree`i'==1;
replace student`i'=0 if retiree`i'==1;
};

forvalues i=1(1)9{;
	egen wage`i'=rowtotal(p6_14_`i'_*);
	gen mainearner`i'=0;
		replace employee`i'=1 if wage`i'>0 & student`i'==0 & oth_inact`i'==0 & disable`i'==0 & housew`i'==0 & 
	unemployed`i'==0 & retiree`i'==0 & selfemployed`i'==0 & employee`i'==0;
	};
	
replace mainearner1=1;

forvalues i=2(1)9{;
	replace mainearner`i'=1 if wage`i'>wage1 & relref`i'==2 & employee`i'==1;
	replace mainearner1=0   if wage`i'>wage1 & relref`i'==2 & employee`i'==1;	
	};	

forvalues i =2(1)9 {;
	gen othcoup`i'=0;
	replace othcoup`i'=1 if married==1 & sex1==0 & sex`i'==1 & relref`i'==2;	
	replace othcoup`i'=1 if married==1 & mainearner`i'==1 & relref`i'==2;
	replace othcoup`i'=1 if married==1 & (housew==1 | student==1) & 
		(unemployed`i'==1 | retiree`i'==1 | selfemployed`i'==1) & relref`i'==2 /*Take the couple when head is housewife */;
	replace sex=sex`i' if othcoup`i'==1;
	replace nac=nac`i' if othcoup`i'==1;
	replace educ=educ`i' if othcoup`i'==1;
	replace health=health`i' if othcoup`i'==1;
	replace employee=employee`i' if othcoup`i'==1;
	replace selfemployed=selfemployed`i' if othcoup`i'==1;
	replace unemployed=unemployed`i' if othcoup`i'==1;
	replace student=student`i' if othcoup`i'==1;
	replace housew=housew`i' if othcoup`i'==1;
	replace oth_inact=oth_inact`i' if othcoup`i'==1;
	replace retiree=retiree`i' if othcoup`i'==1;
	replace health=health`i' if othcoup`i'==1;
	replace univ=univ`i' if othcoup`i'==1;
	replace bankjob=bankjob`i' if othcoup`i'==1;
	};

egen othcoup=rowtotal(othcoup*);

replace sex=sex1 if othcoup==0;
replace nac=nac1 if othcoup==0;
replace educ=educ1 if othcoup==0;
replace health=health1 if othcoup==0;
replace employee=employee1 if othcoup==0;
replace selfemployed=selfemployed1 if othcoup==0;
replace retiree=retiree1 if othcoup==0;
replace disable=disable1 if othcoup==0;
replace student=student1 if othcoup==0;
replace housew=housew1 if othcoup==0;
replace oth_inact=oth_inact1 if othcoup==0;
replace unemployed=unemployed1 if othcoup==0;
replace univ=univ1 if othcoup==0;
replace bankjob=bankjob1 if othcoup==0;

/* Gen dummy to identify status of the couple */;
gen pemployee=0;
gen pselfemployed=0;
gen punemployed=0;
gen pretiree=0;
gen pdisable=0;
gen pstudent=0;
gen phousew=0;
gen poth_inact=0;
gen puniv=0;
gen pnac=0;

forvalues i=2(1)9 {;
	replace punemployed=1 if othcoup`i'==0 & unemployed`i'==1 & relref`i'==2;
	replace pemployee=1 if othcoup`i'==0 & employee`i'==1 & relref`i'==2;
	replace pretiree=1 if othcoup`i'==0 & retiree`i'==1 & relref`i'==2;
	replace pselfemployed=1 if othcoup`i'==0 & selfemployed`i'==1 & relref`i'==2;
	replace pdisable=1 if othcoup`i'==0 & disable`i'==1 & relref`i'==2;
	replace pstudent=1 if othcoup`i'==0 & student`i'==1 & relref`i'==2;
	replace phousew=1 if othcoup`i'==0 & housew`i'==1 & relref`i'==2;
	replace poth_inact=1 if othcoup`i'==0 & oth_inact`i'==1 & relref`i'==2;
	replace puniv=1 if othcoup`i'==0 & univ`i'==1 & relref`i'==2;
	replace pnac=1 if othcoup`i'==0 & nac`i'==1 & relref`i'==2;

	replace punemployed=1 if othcoup`i'==1 & unemployed1==1 & relref`i'==2;
	replace pemployee=1 if othcoup`i'==1 & employee1==1 & relref`i'==2;
	replace pretiree=1 if othcoup`i'==1 & retiree1==1 & relref`i'==2;
	replace pselfemployed=1 if othcoup`i'==1 & selfemployed1==1 & relref`i'==2;
	replace pdisable=1 if othcoup`i'==1 & disable1==1 & relref`i'==2;
	replace pstudent=1 if othcoup`i'==1 & student1==1 & relref`i'==2;
	replace phousew=1 if othcoup`i'==1 & housew1==1 & relref`i'==2;
	replace poth_inact=1 if othcoup`i'==1 & oth_inact1==1 & relref`i'==2;
	replace puniv=1 if othcoup`i'==1 & univ1==1 & relref`i'==2;
	replace pnac=1 if othcoup`i'==1 & nac1==1 & relref`i'==2;
	};
	
* Define other reference person for housew/student households: specifically, take as reference person those sons or daughters that are
main earners;

egen maxw=rowmax(wage1 wage2 wage3 wage4 wage5 wage6 wage7 wage8 wage9);

forvalues i=2(1)9{;
		gen oth_member`i'=0;
		replace oth_member`i'=1 if (housew==1 | student==1) & wage`i'==maxw & maxw>0;
		replace employee`i'=1 if oth_member`i'==1;
		replace sex=sex`i' if oth_member`i'==1;
		*replace psex=0 if oth_member`i'==1 /* Assume has no couple */;
		replace nac=nac`i' if oth_member`i'==1;
		replace pnac=0 if oth_member`i'==1 /* Assume has no couple */;
		replace educ=educ`i' if oth_member`i'==1;
		*replace peduc=0 if oth_member`i'==1 /* Assume has no couple */;
		replace health=health`i' if oth_member`i'==1;
		*replace phealth=0 if oth_member`i'==1 /* Assume has no couple */;
		replace employee=employee`i' if oth_member`i'==1;
		replace pemployee=0 if oth_member`i'==1 /* Assume has no couple */;
		replace selfemployed=selfemployed`i' if oth_member`i'==1;
		replace pselfemployed=0 if oth_member`i'==1 /* Assume has no couple */;
		replace retiree=retiree`i' if oth_member`i'==1;
		replace pretiree=0 if oth_member`i'==1 /* Assume has no couple */;
		replace disable=disable`i' if oth_member`i'==1;
		replace pdisable=0 if oth_member`i'==1 /* Assume has no couple */;
		replace student=student`i' if oth_member`i'==1;
		replace pstudent=0 if oth_member`i'==1 /* Assume has no couple */;
		replace housew=housew`i' if oth_member`i'==1;
		replace phousew=0 if oth_member`i'==1 /* Assume has no couple */;
		replace oth_inact=oth_inact`i' if oth_member`i'==1;
		replace poth_inact=0 if oth_member`i'==1 /* Assume has no couple */;
		replace unemployed=unemployed`i' if oth_member`i'==1;
		replace punemployed=0 if oth_member`i'==1 /* Assume has no couple */;
		replace univ=univ`i' if oth_member`i'==1;
		replace puniv=0 if oth_member`i'==1 /* Assume has no couple */;
		};	


egen auxoth=rowtotal(oth_member*);
		
/* Choose other household member if there are no employees*/;
forvalues i=2(1)9{;
		gen oth2_member`i'=0;
		replace oth2_member`i'=1 if (housew==1 | student==1) & auxoth==0 & selfemployed`i'==1;
		replace selfemployed`i'=1 if oth2_member`i'==1;
		replace sex=sex`i' if oth2_member`i'==1;
		*replace psex=0 if oth_member`i'==1 /* Assume has no couple */;
		replace nac=nac`i' if oth2_member`i'==1;
		replace pnac=0 if oth2_member`i'==1 /* Assume has no couple */;
		replace educ=educ`i' if oth2_member`i'==1;
		*replace peduc=0 if oth_member`i'==1 /* Assume has no couple */;
		replace health=health`i' if oth2_member`i'==1;
		*replace phealth=0 if oth_member`i'==1 /* Assume has no couple */;
		replace employee=employee`i' if oth2_member`i'==1;
		replace pemployee=0 if oth2_member`i'==1 /* Assume has no couple */;
		replace selfemployed=selfemployed`i' if oth2_member`i'==1;
		replace pselfemployed=0 if oth2_member`i'==1 /* Assume has no couple */;
		replace retiree=retiree`i' if oth2_member`i'==1;
		replace pretiree=0 if oth2_member`i'==1 /* Assume has no couple */;
		replace disable=disable`i' if oth2_member`i'==1;
		replace pdisable=0 if oth2_member`i'==1 /* Assume has no couple */;
		replace student=student`i' if oth2_member`i'==1;
		replace pstudent=0 if oth2_member`i'==1 /* Assume has no couple */;
		replace housew=housew`i' if oth2_member`i'==1;
		replace phousew=0 if oth2_member`i'==1 /* Assume has no couple */;
		replace oth_inact=oth_inact`i' if oth2_member`i'==1;
		replace poth_inact=0 if oth2_member`i'==1 /* Assume has no couple */;
		replace unemployed=unemployed`i' if oth2_member`i'==1;
		replace punemployed=0 if oth2_member`i'==1 /* Assume has no couple */;
		replace univ=univ`i' if oth2_member`i'==1;
		replace puniv=0 if oth2_member`i'==1 /* Assume has no couple */;
		};	


gen bhealth=0;
replace bhealth=1 if health>=4;
		
egen auxoth2=rowtotal(oth2_member*);
	
egen aux=rowtotal(employee selfemployed unemployed retiree disable student housew oth_inact);
keep if aux==1;	

gen age=2011-nac;
replace age=age/10;

** Age dummies **;
gen age1=0;
replace age1=1 if age>=3 & age<3.5;

gen age2=0;
replace age2=1 if age>=3.5 & age<4;

gen age3=0;
replace age3=1 if age>=4 & age<4.5;

gen age4=0;
replace age4=1 if age>=4.5 & age<5;

gen age5=0;
replace age5=1 if age>=5 & age<5.5;

gen age6=0;
replace age6=1 if age>=5.5 & age<6;

gen age7=0;
replace age7=1 if age>=6 & age<6.5;

gen age8=0;
replace age8=1 if age>=6.5 & age<7;

gen age9=0;
replace age9=1 if age>=7 & age<7.6;

gen age_inst=0;
replace age_inst=1 if age1==1;
replace age_inst=2 if age2==1;
replace age_inst=3 if age3==1;
replace age_inst=4 if age4==1;
replace age_inst=5 if age5==1;
replace age_inst=6 if age6==1;
replace age_inst=7 if age7==1;
replace age_inst=8 if age8==1;
replace age_inst=9 if age9==1;

gen agesq=age^2;

gen page=2011-nac;
replace page=page/10;

** page dummies **;
gen page1=0;
replace page1=1 if page>=3 & page<3.5;

gen page2=0;
replace page2=1 if page>=3.5 & page<4;

gen page3=0;
replace page3=1 if page>=4 & page<4.5;

gen page4=0;
replace page4=1 if page>=4.5 & page<5;

gen page5=0;
replace page5=1 if page>=5 & page<5.5;

gen page6=0;
replace page6=1 if page>=5.5 & page<6;

gen page7=0;
replace page7=1 if page>=6 & page<6.5;

gen page8=0;
replace page8=1 if page>=6.5 & page<7;

gen page9=0;
replace page9=1 if page>=7 & page<7.6;

gen page_inst=0;
replace page_inst=1 if page1==1;
replace page_inst=2 if page2==1;
replace page_inst=3 if page3==1;
replace page_inst=4 if page4==1;
replace page_inst=5 if page5==1;
replace page_inst=6 if page6==1;
replace page_inst=7 if page7==1;
replace page_inst=8 if page8==1;
replace page_inst=9 if page9==1;

gen pagesq=page^2;



/* Drop multiple-unrelated households */;

egen minval=rowmin(relref*);
replace minval=0 if minval==.;

gen madult=0;
replace madult=1 if minval==9 & (year==2002 | year==2005);
replace madult=1 if minval==12 & (year==2008 | year==2011);


********************************************;
rename p2_3 instal /* Year of house purchasing (assume to be the same as instalment) */;
rename p2_4 price_a /* Purchasing price */;
rename p2_5 price_b /* Price of hypothetical sell */;

		  ******************* Application for loans (2)*****************;

rename p3_12a treject;
rename p3_12b preject;

/* Totally reject loan application (any) */;		  
gen reject=0;
replace reject=1 if treject==1;
replace reject=0 if treject==.;

forvalues i=1(1)4 {;
	rename p3_13s`i' rnoappl`i' /* Reasons of not applying for a loan */;
	rename p3_15s`i' rreject`i' /* Reasons of rejecting */;
	};

	
gen applic2=0;
replace applic2=1 if rnoappl1==.;

/* Discouraged borrowers: refuse to apply for a loan because it would be turned down (any member of the household. Exclude debt holders */;
gen discour=0;
replace discour=1 if (rnoappl1==4 | rnoappl2==4 | rnoappl3==4 | rnoappl4==4) & anydebt==0 & applic2==0;

/* Applicant: whether the household made any loan application or refused beacuse of sure rejecting */;
gen applic=0;
replace applic=1 if applic2>0 | discour==1 | anydebt==1;

/* Partially rejected loan application (any) */;
gen partrej=0;
replace partrej=1 if preject==1;
replace partrej=0 if preject==.;
		
gen totpartrej=0;
replace totpartrej=1 if (reject==1 | partrej==1);
replace totpartrej=1 if discour==1;
*replace totpartrej=0 if anydebt==1;

/* Rationed: discouraged or reject totally or partially */;
gen ration2=0;
replace ration2=1 if discour==1 | partrej==1 | reject==1;
replace ration2=0 if ration2==.;
*replace ration2=0 if anydebt==1;

/* Rationed: discouraged or totally rejected */;
gen ration=0;
replace ration=1 if discour==1 | reject==1;
replace ration=0 if ration==.;
*replace ration=0 if anydebt==1;

*replace anydebt=1 if applic==1 & anydebt==0 & ration==0 /* Applied, borrowed and repaid, and report zero borrowing */;




/*;
		  ******************* Application for loans ********************;

rename p3_14 nreject /* number of applications rejected */;

/* Totally reject loan application (any) */;
gen reject=0;
replace reject=1 if nreject>0;
replace reject=0 if nreject==.;

forvalues i=1(1)5 {;
	rename p3_13s`i' rnoappl`i' /* Reasons of not applying for a loan */;
	rename p3_15s`i' rreject`i' /* Reasons of rejecting */;
	};

rename p3_12 napplic /* Number of no applications made in last two years */;

/* Discouraged borrowers: refuse to apply for a loan because it would be turned down (any member of the household. Exclude debt holders */;
gen discour=0;
replace discour=1 if (rnoappl1==4 | rnoappl2==4 | rnoappl3==4 | rnoappl4==4 | rnoappl5==4) & anydebt==0 & napplic==0;


/* Applicant: whether the household made any loan application or refused beacuse of sure rejecting */;
gen applic=0;
replace applic=1 if napplic>0 | discour==1 | anydebt==1;
* replace applic=0 if ration==0 & anydebt==0 /* Applied, accepted but did not take the loan (we think they took the loan and repaid the debt) */;

* gen applic_non_disc=0;
* replace applic_non_disc=1 if napplic>0 | anydebt==1;


rename p3_16 npartrej /* # times granted smaller amount than asked for */;



/* Partially rejected loan application (any) */;
gen partrej=0;
replace partrej=1 if npartrej>0;
replace partrej=0 if npartrej==.;

gen totpartrej=0;
replace totpartrej=1 if (reject==1 | partrej==1);
replace totpartrej=1 if discour==1;
*replace totpartrej=0 if anydebt==1;

/* Rationed: discouraged or reject totally or partially */;
gen ration2=0;
replace ration2=1 if discour==1 | partrej==1 | reject==1;
replace ration2=0 if ration2==.;
*replace ration2=0 if anydebt==1;

/* Rationed: discouraged or totally rejected */;
gen ration=0;
replace ration=1 if discour==1 | reject==1;
replace ration=0 if ration==.;
*replace ration=0 if anydebt==1;

replace anydebt=1 if applic==1 & anydebt==0 & ration==0 /* Applied, borrowed and repaid, and report zero borrowing */;


/* Another definition is made 200 lines or more in advanced (guess that it was done in Venice)
/* Partially and Totally rationed */;

gen totpartrej=0;
replace totpartrej=1 if reject==1 | partrej==1;
*/;

*/;



/*;
************* EMPLOYMENT SITUATION (reference person) *************;

rename p6_1c1_1 employee;
rename p6_1c2_1 selfemployed;
rename p6_1c3_1 unemployed;
rename p6_1c4_1 retiree;
rename p6_1c5_1 disable /* Permanently disabled */;
rename p6_1c6_1 student;


************* EMPLOYMENT SITUATION (reference person "partner") ***********;
gen pemployee=0 /* Partner is an employee */;
replace pemployee=1 if (married==1 & p6_1c1_2==1 & relref2==2) |
					   (married==1 & p6_1c1_3==1 & relref3==2) |
					   (married==1 & p6_1c1_4==1 & relref4==2) |
					   (married==1 & p6_1c1_5==1 & relref5==2) |
					   (married==1 & p6_1c1_6==1 & relref6==2) |
					   (married==1 & p6_1c1_7==1 & relref7==2) |
					   (married==1 & p6_1c1_8==1 & relref8==2) |
					   (married==1 & p6_1c1_9==1 & relref9==2) ;
					   
gen pselfemployed=0 /* Partner is selfemployed */;
replace pselfemployed=1 if (married==1 & p6_1c2_2==1 & relref2==2) |
						   (married==1 & p6_1c2_3==1 & relref3==2) |
					       (married==1 & p6_1c2_4==1 & relref4==2) |
					       (married==1 & p6_1c2_5==1 & relref5==2) |
					       (married==1 & p6_1c2_6==1 & relref6==2) |
					       (married==1 & p6_1c2_7==1 & relref7==2) |
					       (married==1 & p6_1c2_8==1 & relref8==2) |
					       (married==1 & p6_1c2_9==1 & relref9==2) ;
			

gen punemployed=0 /* Partner is unemployed */;
replace punemployed=1 if   (married==1 & p6_1c3_2==1 & relref2==2) |
						   (married==1 & p6_1c3_3==1 & relref3==2) |
					       (married==1 & p6_1c3_4==1 & relref4==2) |
					       (married==1 & p6_1c3_5==1 & relref5==2) |
					       (married==1 & p6_1c3_6==1 & relref6==2) |
					       (married==1 & p6_1c3_7==1 & relref7==2) |
					       (married==1 & p6_1c3_8==1 & relref8==2) |
					       (married==1 & p6_1c3_9==1 & relref9==2) ;
						   
gen pretiree=0 /* Partner is retiree */;
replace pretiree=1 if      (married==1 & p6_1c4_2==1 & relref2==2) |
						   (married==1 & p6_1c4_3==1 & relref3==2) |
					       (married==1 & p6_1c4_4==1 & relref4==2) |
					       (married==1 & p6_1c4_5==1 & relref5==2) |
					       (married==1 & p6_1c4_6==1 & relref6==2) |
					       (married==1 & p6_1c4_7==1 & relref7==2) |
					       (married==1 & p6_1c4_8==1 & relref8==2) |
					       (married==1 & p6_1c4_9==1 & relref9==2) ;
						   
gen pdisable=0 /* Partner is disabled */;
replace pdisable=1 if      (married==1 & p6_1c5_2==1 & relref2==2) |
						   (married==1 & p6_1c5_3==1 & relref3==2) |
					       (married==1 & p6_1c5_4==1 & relref4==2) |
					       (married==1 & p6_1c5_5==1 & relref5==2) |
					       (married==1 & p6_1c5_6==1 & relref6==2) |
					       (married==1 & p6_1c5_7==1 & relref7==2) |
					       (married==1 & p6_1c5_8==1 & relref8==2) |
					       (married==1 & p6_1c5_9==1 & relref9==2) ;

*/;
						   
**************** INCOME *********************;
*rename renthog hhincome /* annual 2001 for 2002 wave, 2004 (2005 wave), 2007 (2008 wave) */;
replace hhincome=hhincome/acpi*100;
gen lincome=log(1+hhincome);
replace hhincome=hhincome/10000;
gen hhincomesq=(hhincome^2)/10000;

rename mrenthog mhhincome /* month oct2002 - may2003 (2002), nov2005 - may2006 (2005), nov2008 - jun2009 (2008) */;
replace mhhincome=mhhincome/mcpi*100;
gen mhhincomesq=mhhincome^2;


************** FINANCIAL HELP FROM RELATIVES AND FRIENDS *******************;
/*monetary assistance from friends or family members outside the
household, or from a partner no longer living in the household*/;

rename p6_59 finhelp;
replace finhelp=0 if finhelp==2;

rename p6_60 amounthelp;
replace amounthelp=amounthelp/mcpi*100;

************ ARREARS *****************;

/* In the last twelve months have you had any financial
difficulties which resulted in your delaying the payment of any of
your debts? */;

gen arrears=0;
replace arrears=1 if p9_16==1;

*replace anydebt=1 if arrears==1;
replace applic=1 if anydebt==1;
*replace ration=0 if arrears==1;
replace discour=0 if anydebt==1;

gen applic_non_disc=0;
replace applic_non_disc=1 if applic==1 & discour==0;

gen repay=.;
replace repay=1 if arrears==0 & anydebt==1;
replace repay=0 if arrears==1;

* Risk Aversion;
rename p9_11 riskaver;

gen risklot=.;
replace risklot=0 if riskaver==2 | riskaver==3 | riskaver==4;
replace risklot=1 if riskaver==1;

gen riskfair=.;
replace riskfair=0 if riskaver==1 | riskaver==3 | riskaver==4;
replace riskfair=1 if riskaver==2;

gen risksome=.;
replace risksome=0 if riskaver==1 | riskaver==2 | riskaver==4;
replace risksome=1 if riskaver==3;

gen norisk=.;
replace norisk=0 if riskaver==1 | riskaver==2 | riskaver==3;
replace norisk=1 if riskaver==4;

******** Dummies for hhincome ********;
_pctile hhincome, p(20,40,60,80);
scalar r1=r(r1);
scalar r2=r(r2);
scalar r3=r(r3);
scalar r4=r(r4);

gen hhincome1=0;
replace hhincome1=1 if hhincome<scalar(r1);

gen hhincome2=0;
replace hhincome2=1 if hhincome>=scalar(r1) & hhincome<scalar(r2);

gen hhincome3=0;
replace hhincome3=1 if hhincome>=scalar(r2) & hhincome<scalar(r3);

gen hhincome4=0;
replace hhincome4=1 if hhincome>=scalar(r3)  & hhincome<scalar(r4);

gen hhincome5=0;
replace hhincome5=1 if hhincome>scalar(r4);

gen inc_inst=0;
replace inc_inst=1 if hhincome1==1;
replace inc_inst=2 if hhincome2==1;
replace inc_inst=3 if hhincome3==1;
replace inc_inst=4 if hhincome4==1;


*********** Dummies for income II ************;
replace hhincome=hhincome*10000;

gen hh1=0;
replace hh1=1 if hhincome<=15000;
gen hh2=0;
replace hh2=1 if hhincome>15000 & hhincome<=25000;
gen hh3=0;
replace hh3=1 if hhincome>25000 & hhincome<=35000;
gen hh4=0;
replace hh4=1 if hhincome>35000 & hhincome<=45000;
gen hh5=0;
replace hh5=1 if hhincome>45000 & hhincome<=57000;
gen hh6=0;
replace hh6=1 if hhincome>57000;
*/;
gen hh_inst=0;
replace hh_inst=1 if hh1==1;
replace hh_inst=2 if hh2==1;
replace hh_inst=3 if hh3==1;
replace hh_inst=4 if hh4==1;
replace hh_inst=5 if hh5==1;
replace hh_inst=6 if hh6==1;
*replace hh_inst=7 if hh7==1;
*replace hh_inst=8 if hh8==1;
*replace hh_inst=9 if hh9==1;

replace hhincome=hhincome/10000;

*********** Dummies for nwealth ************;

replace nwealth=nwealth/acpi*100;
gen lnwealth=.;
replace lnwealth=log(1+abs(nwealth)) if nwealth>=0;
replace lnwealth=-log(1+abs(nwealth)) if nwealth<0;

gen nw1=0;
replace nw1=1 if nwealth<=10000;
gen nw2=0;
replace nw2=1 if nwealth>10000 & nwealth<=80000;
gen nw3=0;
replace nw3=1 if nwealth>80000 & nwealth<=200000;
gen nw4=0;
replace nw4=1 if nwealth>200000 & nwealth<=500000;
gen nw5=0;
replace nw5=1 if nwealth>500000;


***** Generate alternative wealth variables *****;
gen housewealth= nwealth;
replace housewealth=housewealth-vmresid/acpi*100+vdebtmresid/acpi*100 if debtmresid==1;

replace housewealth=housewealth + vdebtprop1/acpi*100 - p2_39_1*(p2_37_1/100)/acpi*100 if vdebtprop1>0;
replace housewealth=housewealth + vdebtprop2/acpi*100 - p2_39_2*(p2_37_1/100)/acpi*100 if vdebtprop2>0;
replace housewealth=housewealth + vdebtprop3/acpi*100 - p2_39_3*(p2_37_1/100)/acpi*100 if vdebtprop3>0;
replace housewealth=housewealth + vdebtprop4/acpi*100 - p2_39_4*(p2_37_1/100)/acpi*100 if vdebtprop4>0;

gen lhousingw=.;
replace lhousingw=log(1+abs(housewealth)) if housewealth>=0;
replace lhousingw=-log(1+abs(housewealth)) if housewealth<0;

gen buswealth=nwealth;
replace buswealth=buswealth-valhog/acpi*100+vbusloan;

gen lbusloanw=.;
replace lbusloanw=log(1+abs(buswealth)) if buswealth>=0;
replace lbusloanw=-log(1+abs(buswealth)) if buswealth<0;

gen cardwealth=nwealth;
replace cardwealth=cardwealth+vcredcard;

gen lcredcardw=.;
replace lcredcardw=log(1+abs(cardwealth)) if cardwealth>=0;
replace lcredcardw=-log(1+abs(cardwealth)) if cardwealth<0;

gen otherwealth=nwealth;
replace otherwealth=otherwealth-vrestbis;

gen lrestbisw=.;
replace lrestbisw=log(1+abs(otherwealth)) if otherwealth>=0;
replace lrestbisw=-log(1+abs(otherwealth)) if otherwealth<0;
*********** Dummies for housing wealth ************;

gen housingw1=0;
replace housingw1=1 if housewealth<=10000;
gen housingw2=0;
replace housingw2=1 if housewealth>10000 & housewealth<=80000;
gen housingw3=0;
replace housingw3=1 if housewealth>80000 & housewealth<=200000;
gen housingw4=0;
replace housingw4=1 if housewealth>200000 & housewealth<=500000;
gen housingw5=0;
replace housingw5=1 if housewealth>500000;

*********** Dummies for business wealth ************;

gen busloanw1=0;
replace busloanw1=1 if buswealth<=10000;
gen busloanw2=0;
replace busloanw2=1 if buswealth>10000 & buswealth<=80000;
gen busloanw3=0;
replace busloanw3=1 if buswealth>80000 & buswealth<=200000;
gen busloanw4=0;
replace busloanw4=1 if buswealth>200000 & buswealth<=500000;
gen busloanw5=0;
replace busloanw5=1 if buswealth>500000;

*********** Dummies for credit card wealth ************;

gen credcardw1=0;
replace credcardw1=1 if cardwealth<=10000;
gen credcardw2=0;
replace credcardw2=1 if cardwealth>10000 & cardwealth<=80000;
gen credcardw3=0;
replace credcardw3=1 if cardwealth>80000 & cardwealth<=200000;
gen credcardw4=0;
replace credcardw4=1 if cardwealth>200000 & cardwealth<=500000;
gen credcardw5=0;
replace credcardw5=1 if cardwealth>500000;


*********** Dummies for other debts wealth ************;

gen restbisw1=0;
replace restbisw1=1 if otherwealth<=10000;
gen restbisw2=0;
replace restbisw2=1 if otherwealth>10000 & otherwealth<=80000;
gen restbisw3=0;
replace restbisw3=1 if otherwealth>80000 & otherwealth<=200000;
gen restbisw4=0;
replace restbisw4=1 if otherwealth>200000 & otherwealth<=500000;
gen restbisw5=0;
replace restbisw5=1 if otherwealth>500000;


foreach f of var * { ;
	rename `f' `f'_imp`x' ;
} ;
rename h_2011_imp`x' h2011;
drop p6*;
save wave2011_imp`x'.dta, replace;

};

cd "H:\Mi unidad\Grant_new\EFF";
use "H:\Mi unidad\Grant_new\EFF\Imputation1\wave2011_imp1.dta";
joinby h2011 using "H:\Mi unidad\Grant_new\EFF\Imputation2\wave2011_imp2";
joinby h2011 using "H:\Mi unidad\Grant_new\EFF\Imputation3\wave2011_imp3";
joinby h2011 using "H:\Mi unidad\Grant_new\EFF\Imputation4\wave2011_imp4";
joinby h2011 using "H:\Mi unidad\Grant_new\EFF\Imputation5\wave2011_imp5";



save "H:\Mi unidad\Grant_new\wave2011.dta", replace;

erase "H:\Mi unidad\Grant_new\EFF\Imputation1\wave2011_imp1.dta";
erase "H:\Mi unidad\Grant_new\EFF\Imputation2\wave2011_imp2.dta";
erase "H:\Mi unidad\Grant_new\EFF\Imputation3\wave2011_imp3.dta";
erase "H:\Mi unidad\Grant_new\EFF\Imputation4\wave2011_imp4.dta";
erase "H:\Mi unidad\Grant_new\EFF\Imputation5\wave2011_imp5.dta";

*************************************************************************;
************************************* 2014 ******************************;
*************************************************************************;

foreach x in 1 2 3 4 5{; 


cd "H:\Mi unidad\Grant_new\EFF\Imputation`x'";

use seccion6_2014_imp`x'.dta, clear;

joinby h_2014 using otras_secciones_2014_imp`x'.dta;

gen year=2014;

********************************************************************;
** Annual and monthly consumer price index to be used (base 2010) **;
********************************************************************;

gen acpi=81.06;
replace acpi=88.96 if year==2005;
replace acpi=98.52 if year==2008;
replace acpi=103.20 if year==2011;
replace acpi=107.05 if year==2014;

gen mcpi=82.73 					 /* mean oct02-may03 */;
replace mcpi=91.14 if year==2005 /* mean nov05-may06 */;
replace mcpi=98.10 if year==2008 /* mean nov08-jun09 */;
replace mcpi=104.33 if year==2011 /* mean oct11-apr12 */;
replace mcpi=106.42 if year==2014 /* mean sept14-mar15*/;

********************************************************************;
********************************************************************;

*NET WEALTH AND INCOME;

*1.- FOR THE PERCENTAGE OF HOUSEHOLDS OWNING THAT ASSET;

*REAL ASSETS;

*MAIN RESIDENCE;
*To calculate the percentage of households that own their main residence we use the variable p2_1;

gen np2_1=(p2_1==2 & p2_5>0 & p2_5~=.);

gen owner=0;
replace owner=1 if np2_1==1;

gen renter=0 /*renter or (only 2014) renter with purchase option*/;
replace renter=1 if p2_1==1;

gen freeuse=0;
replace freeuse=1 if p2_1==3;

*OTHER REAL ESTATE PROPERTIES;
*To calculate the percentage of households that own other real estate properties we use the variable np2_32; 
gen np2_32=((p2_32==1 & p2_33>=1 & p2_33~=. & p2_39_1>0 & p2_39_1~=.)|
            (p2_32==1 & p2_33>=2 & p2_33~=. & p2_39_2>0 & p2_39_2~=.)|
            (p2_32==1 & p2_33>=3 & p2_33~=. & p2_39_3>0 & p2_39_3~=.)|
            (p2_32==1 & p2_33>3  & p2_33~=. & p2_39_4>0 & p2_39_4~=.));

gen othowner=.;
replace othowner=1 if np2_32==1;
replace othowner=0 if np2_32==0;

*JEWELLERY, WORKS OF ART, ANTIQUES;
*To calculate the percentage of households that own jewellery, works of art and antiques we use the variable np2_82;
gen np2_82=(p2_82==1 & p2_84>0 & p2_84~=.);

gen jewel=.;
replace jewel=0 if np2_82==0;
replace jewel=1 if np2_82==1;


*VALOR DEL NEGOCIO POR TRABAJOS POR CUENTA PROPIA;
*VALUE OF BUSINESSES RELATED TO SELF-EMPLOYMENT;
gen haveneg =(p4_101==1);

gen valhog =0;
replace valhog =valhog + p4_111_1 if p4_101==1 & p4_111_1>0 & p4_111_1~=.;
replace valhog =valhog + p4_111_2 if p4_101==1 & p4_111_2>0 & p4_111_2~=.;
replace valhog =valhog + p4_111_3 if p4_101==1 & p4_111_3>0 & p4_111_3~=.;
replace valhog =valhog + p4_111_4 if p4_101==1 & p4_111_4>0 & p4_111_4~=.;
replace valhog =valhog + p4_111_5 if p4_101==1 & p4_111_5>0 & p4_111_5~=.;
replace valhog =valhog + p4_111_6 if p4_101==1 & p4_111_6>0 & p4_111_6~=.;

gen havenegval =(haveneg==1 & valhog>0);


*ALGUN TIPO DE ACTIVO REAL;
*SOME KIND OF REAL ASSET;

gen  tienereal=(np2_1==1|np2_32==1|np2_82==1| havenegval==1);


*ACTIVOS FINANCIEROS;
*FINANCIAL ASSETS;


*ACCOUNTS AND DEPOSITS USABLE FOR PAYMENTS;
*To calculate the percentage of households that own accounts and deposits usable for payments and that declare a strictly positive value 
*for the balance of those accounts we generate a new variable;

gen np4_5=(p4_5==1 & p4_7_3>0 & p4_7_3~=.);
rename np4_5 account_pay;
label var account_pay "households that own accounts and deposits usable for payments and that declare a strictly positive value";

*LISTED SHARES;
*To calculate the percentage of households that own listed and that declare a strictly positive value for that portfolio we generate a new variable;

gen np4_10=(p4_10==1 & p4_15>0 & p4_15~=.);

rename np4_10 listshare;
label var listshare "household that own listed shares";


*UNLISTED SHARES AND OTHER EQUITY;
*To calculate the percentage of households that own unlisted shares and other equity and that declare a strictly positive
* value for that portfolio we generate a new variable;

gen np4_18=(p4_18==1 & p4_24>0 & p4_24~=.);
rename np4_18 unlistshare;
label var unlistshare "household that own unlisted shares and other equity";


*FIXED-INCOME SECURITIES;
*To calculate the percentage of households that own fixed-income securities and that declare a strictly positive value for that portfolio we generate a new variable;

gen np4_33=(p4_33==1 & p4_35>0 & p4_35~=.);

rename np4_33 fixsec;
label var fixsec "household that own fixed-income securities ";

*MUTUAL FUNDS (FFII);
*To calculate the percentage of households that own mutual funds and that declare a strictly positive value for that portfolio we generate a new variable;

gen np4_27=((p4_27==1 & p4_28>=1 & p4_28~=. & p4_31_1>0 & p4_31_1~=.)|
            (p4_27==1 & p4_28>=2 & p4_28~=. & p4_31_2>0 & p4_31_2~=.)|
            (p4_27==1 & p4_28>=3 & p4_28~=. & p4_31_3>0 & p4_31_3~=.)|
            (p4_27==1 & p4_28>=4 & p4_28~=. & p4_31_4>0 & p4_31_4~=.)|
            (p4_27==1 & p4_28>=5 & p4_28~=. & p4_31_5>0 & p4_31_5~=.)|
            (p4_27==1 & p4_28>=6 & p4_28~=. & p4_31_6>0 & p4_31_6~=.)|
            (p4_27==1 & p4_28>=7 & p4_28~=. & p4_31_7>0 & p4_31_7~=.)|
            (p4_27==1 & p4_28>=8 & p4_28~=. & p4_31_8>0 & p4_31_8~=.)|
            (p4_27==1 & p4_28>=9 & p4_28~=. & p4_31_9>0 & p4_31_9~=.)|
            (p4_27==1 & p4_28>9 & p4_28~=. & p4_31_10>0 & p4_31_10~=.));

rename np4_27 mutfunds;
label var mutfunds "household that own mutual funds";

*CUENTAS VIVIENDA Y CUENTAS NO UTILIZABLES PARA REALIZAR PAGOS;
*Para calcular la proporción de hogares que poseen cuentas y depósitos no utilizables para realizar pagos generamos una nueva variable cuentas;

*HOUSE-PURCHASE SAVINGS ACCOUNTS AND ACCOUNTS NOT USABLE FOR PAYMENTS;
*To calculate the percentage of households that own house-purchase saving accounts and/or accounts not usable for payments and 
*that declare a strictly positive value for the balance of those accounts we generate a new variable;

gen cuentas=((p4_3==1 & p4_7_1>0 & p4_7_1~=.)|(p4_4==1 & p4_7_2>0 & p4_7_2~=.));

rename cuentas account_nopay;
label var account_nopay "household that own accounts and deposits not usable for payments";


*PENSION SCHEMES (plan pensiones);
*To calculate the percentage of households that own pension schemes and that declare a strictly positive value for the balance of those pension schemes we generate a new variable;

gen np5_1=((p5_1==1 & p5_1a>=1 & p5_1a~=. & p5_7_1>0 & p5_7_1~=.)|
           (p5_1==1 & p5_1a>=2 & p5_1a~=. & p5_7_2>0 & p5_7_2~=.)|
           (p5_1==1 & p5_1a>=3 & p5_1a~=. & p5_7_3>0 & p5_7_3~=.)|
           (p5_1==1 & p5_1a>=4 & p5_1a~=. & p5_7_4>0 & p5_7_4~=.)|
           (p5_1==1 & p5_1a>=5 & p5_1a~=. & p5_7_5>0 & p5_7_5~=.)|
           (p5_1==1 & p5_1a>=6 & p5_1a~=. & p5_7_6>0 & p5_7_6~=.)|
           (p5_1==1 & p5_1a>=7 & p5_1a~=. & p5_7_7>0 & p5_7_7~=.)|
           (p5_1==1 & p5_1a>=8 & p5_1a~=. & p5_7_8>0 & p5_7_8~=.)|
           (p5_1==1 & p5_1a>=9 & p5_1a~=. & p5_7_9>0 & p5_7_9~=.)|
           (p5_1==1 & p5_1a>9 & p5_1a~=. & p5_7_10>0 & p5_7_10~=.));

rename np5_1 penplan;
label var penplan "household that own pension schemes";
*SEGUROS DE VIDA;
*Para calcular la proporción de hogares que tienen seguros tipo unit linked o mixto generamos una nueva variable;

*To calculate the percentage of households that own unit-linked or mixed life insurance we generate a new variable;

gen seguro=((p5_9a==1 & p5_10a>=1 & p5_10a~=. & p5_13_1==2 & p5_14_1>0 & p5_14_1~=.)|
                    (p5_9a==1 & p5_10a>=2 & p5_10a~=. & p5_13_2==2 & p5_14_2>0 & p5_14_2~=.)|
                    (p5_9a==1 & p5_10a>=3 & p5_10a~=. & p5_13_3==2 & p5_14_3>0 & p5_14_3~=.)|
                    (p5_9a==1 & p5_10a>=4 & p5_10a~=. & p5_13_4==2 & p5_14_4>0 & p5_14_4~=.)|
                    (p5_9a==1 & p5_10a>=5 & p5_10a~=. & p5_13_5==2 & p5_14_5>0 & p5_14_5~=.)|
                    (p5_9a==1 & p5_10a>5 &   p5_10a~=. & p5_13_6==2 & p5_14_6>0 & p5_14_6~=.)|
	       (p5_9a==1 & p5_10a>=1 & p5_10a~=. & p5_13_1==3 & p5_14_1>0 & p5_14_1~=.)|
                    (p5_9a==1 & p5_10a>=2 & p5_10a~=. & p5_13_2==3 & p5_14_2>0 & p5_14_2~=.)|
                    (p5_9a==1 & p5_10a>=3 & p5_10a~=. & p5_13_3==3 & p5_14_3>0 & p5_14_3~=.)|
                    (p5_9a==1 & p5_10a>=4 & p5_10a~=. & p5_13_4==3 & p5_14_4>0 & p5_14_4~=.)|
                    (p5_9a==1 & p5_10a>=5 & p5_10a~=. & p5_13_5==3 & p5_14_5>0 & p5_14_5~=.)|
                    (p5_9a==1 & p5_10a>5 &   p5_10a~=. & p5_13_6==3 & p5_14_6>0 & p5_14_6~=.));	

rename seguro lifeinsur;
label var lifeinsur "household that own unit-linked or mixed life insurance";

*PLANES DE PENSIONES INCLUYENDO SEGUROS DE VIDA DE INVERSION O MIXTOS;
*PENSION SCHEMES INCLUDING UNIT-LINKED OR MIXED LIFE INSURANCE;

gen penseg=(penplan==1|lifeinsur==1);

*PORTFOLIOS UNDER MANAGEMENT (carteras gestionadas);

gen cart_gest=((p4_41==1 & p4_42==1) & p4_43>0 & p4_43~=.);


*OTHER FINANCIAL ASSETS; 

*To calculate the percentage of households to whom the business or other people owe money we generate the variable sideuda; 


*PROGRAMA PARA CALCULAR LO QUE LES DEBEN LOS NEGOCIOS A LOS DISTINTOS MIEMBROS DEL HOGAR (P4_116);
*PROGRAM TO OBTAIN WHAT THE BUSINESSES OWE TO THE DIFFERENT HOUSEHOLD MEMBERS (P4_116);

gen valdeuhog=0;
gen havedeuhog=0;
forvalues m=1/6   {;
	replace valdeuhog=valdeuhog+p4_116_`m' if (p4_116_`m'>0 & p4_116_`m'~=.);
	replace havedeuhog=1 if (p4_115_`m'==1);
	};
gen sideuda=((havedeuhog ==1 & valdeuhog>0)|(p4_37==1 & p4_38>0 & p4_38~=.));

rename sideuda creditor;
label var creditor "household to whom the business or other people owe money";

*ALGUN TIPO DE ACTIVO FINANCIERO;
*SOME TYPE OF FINANCIAL ASSET;

gen tienefin=(account_pay==1|listshare==1|unlistshare==1|fixsec==1|mutfunds==1|account_nopay==1|penplan==1|lifeinsur==1|creditor==1|cart_gest==1);

*ALGUN TIPO DE ACTIVO;
*SOME TYPE OF ASSET;

gen tiene=(tienereal==1|tienefin==1);
rename tiene anyasset;




*2.- PARA EL VALOR DE DICHOS ACTIVOS;
*2.- FOR THE VALUE OF THOSE ASSETS;

*ACTIVOS REALES;
*REAL ASSETS;

*MAIN RESIDENCE;
*To obtain the value of the main residence we use the variable p2_5;
gen np2_5=p2_5 if p2_1b==1;
replace np2_5=p2_5*(p2_1c/100) if p2_1b==2;

rename np2_5 vmresid;
label var vmresid "value of the main residence";

*OTHER REAL ESTATE PROPERTIES;
*To obtain the value of the other real estate properties we generate a new variable;

gen otraspr=0;
replace otraspr=otraspr+p2_39_1*(p2_37_1/100) if (p2_33>=1 & p2_33~=. & p2_39_1>=0 & p2_39_1~=. & p2_37_1>0 & p2_37_1~=.);
replace otraspr=otraspr+p2_39_2 *(p2_37_2/100) if (p2_33>=2 & p2_33~=. & p2_39_2>=0 & p2_39_2~=. & p2_37_2>0 & p2_37_2~=.);
replace otraspr=otraspr+p2_39_3* (p2_37_3/100) if (p2_33>=3 & p2_33~=. & p2_39_3>=0 & p2_39_3~=. & p2_37_3>0 & p2_37_3~=.);
replace otraspr=otraspr+p2_39_4 if (p2_33>3 & p2_33~=. & p2_39_4>=0 & p2_39_4~=.);

rename otraspr vothprop;
label var vothprop "value of the other real estate properties";


*JEWELLERY, WORKS OF ART, ANTIQUES;
*To obtain the value of the jewellery, works of art and antiques we use the variable p2_84;
rename p2_84 vjewel;
label var vjewel "value of the jewellery, works of art and antiques";

*VALOR DEL NEGOCIO POR TRABAJOS POR CUENTA PROPIA;
*la mediana del valor del negocio será la mediana de valhog if havenegval==1; 

*TBD;

*VALUE OF THE BUSINESS RELATED TO SELF-EMPLOYMENT;
*The median of the business value is equal to the median of valhog if havenegval==1;


*ACTIVOS FINANCIEROS;
*FINANCIAL ASSETS;

*CUENTAS Y DEPOSITOS UTILIZABLES PARA REALIZAR PAGOS;
*Para calcular el saldo de las cuentas y depósitos para realizar pagos utilizamos la variable p4_7_3;


*ACCOUNTS AND DEPOSITS USABLE FOR PAYMENTS;
*To obtain the balance of the accounts and deposits usable for payments we use the variable p4_7_3;
rename p4_7_3 vaccount_pay;



*ACCIONES COTIZADAS EN BOLSA;
*Para calcular el valor de las acciones cotizadas utilizamos la variable p4_15;


*LISTED SHARES;
*To obtain the value of the listed shares we use the variable p4_15;
rename p4_15 vlistshare;

*ACCIONES NO COTIZADAS EN BOLSA Y PARTICIPACIONES;
*Para calcular el valor de las acciones no cotizadas y participaciones utilizamos la variable p4_24;

*UNLISTED SHARES ANDOTHER EQUITY;
*To obtain the value of the unlisted shares and other equity we use the variable p4_24;
rename p4_24 vunlist;

*VALORES DE RENTA FIJA;
*Para calcular el valor de los valores de renta fija utilizamos la variable p4_35;

*FIXED-INCOME SECURITIES;
*To obtain the value of the fixed-income securities we use the variable p4_35;

rename p4_35 vfixsec;

*FONDOS DE INVERSION;
*Para calcular el valor total de los fondos de inversión utilizamos la variable allf calculada como (i) la suma de los valores de cada uno de los fondos 
*de inversión que posee el hogar (p4_31_i, i=1,…,10) si el número de estos fondos es menor o igual a 10, y (ii) el valor total de los fondos de inversión 
*del hogar si posee más de 10 fondos (p4_28a);

*MUTUAL FUNDS;
*To obtain the total value of mutual funds we use the variable allf calculated as (i) the addition of the values of each mutual fund that the household
* owns (p4_31_i, i=1,…,10) if the number of these funds is 10 or less, and (ii) the household mutual funds’ total value if this one owns more than 10 (p4_28a);

egen allf=rowtotal(p4_31*);
replace allf=p4_28a if p4_28>10;
label var allf "Total value of mutual funds";


*CUENTAS VIVIENDA Y CUENTAS NO UTILIZABLES PARA REALIZAR PAGOS;
*Para calcular el saldo de las cuentas y depósitos no utilizables para realizar pagos generamos una nueva variable;

*HOME-PURCHASE SAVINGS ACCOUNTS AND ACCOUNTS NOT USABLE FOR PAYMENTS;
*To obtain the balance of the accounts and deposits not usable for payments we generate a new variable;  

gen salcuentas=0;
replace salcuentas = salcuentas +p4_7_1 if p4_3==1;
replace salcuentas = salcuentas + p4_7_2 if p4_4==1;

rename salcuentas vaccount_nopay;
label var vaccount_nopay "balance of the accounts and deposits not usable for payments";

*PLANES DE PENSIONES;
*Para calcular valor actualizado de los planes de pensiones generamos una nueva variable;

*PENSION SCHEMES;
*To obtain the current value of the pension schemes we generate a new variable;

gen valor=0; 
replace valor = valor +p5_7_1 if (p5_1==1 & p5_7_1>=0 & p5_7_1~=. );
replace valor = valor + p5_7_2 if (p5_1==1 & p5_7_2>=0 & p5_7_2~=.);
replace valor = valor + p5_7_3 if (p5_1==1 & p5_7_3>=0 & p5_7_3~=.);
replace valor = valor + p5_7_4 if (p5_1==1 & p5_7_4>=0 & p5_7_4~=.);
replace valor = valor + p5_7_5 if (p5_1==1 & p5_7_5>=0 & p5_7_5~=.);
replace valor = valor + p5_7_6 if (p5_1==1 & p5_7_6>=0 & p5_7_6~=.);
replace valor = valor + p5_7_7 if (p5_1==1 & p5_7_7>=0 & p5_7_7~=.);
replace valor = valor + p5_7_8 if (p5_1==1 & p5_7_8>=0 & p5_7_8~=.);
replace valor = valor + p5_7_9 if (p5_1==1 & p5_7_9>=0 & p5_7_9~=.);
replace valor = valor + p5_7_10 if (p5_1==1 & p5_7_10>=0 & p5_7_10~=.);


rename valor vpenplan;
label var vpenplan "current value of the pension schemes";

*No consideramos las mutualidades;
*We do not consider mutual insurance;

*SEGUROS DE VIDA;
*Para calcular el valor de estos seguros tipo unit linked o mixto generamos una nueva variable;

*LIFE INSURANCE;
*To obtain the value of the unit-linked or mixed life insurance we generate a new variable;


gen valseg=0;
replace valseg = valseg +p5_14_1 if ((p5_13_1==2| p5_13_1==3) & p5_14_1>=0 & p5_14_1~=.);
replace valseg = valseg +p5_14_2 if ((p5_13_2==2| p5_13_2==3) & p5_14_2>=0 & p5_14_2~=.);
replace valseg = valseg +p5_14_3 if ((p5_13_3==2| p5_13_3==3) & p5_14_3>=0 & p5_14_3~=.);
replace valseg = valseg +p5_14_4 if ((p5_13_4==2| p5_13_4==3) & p5_14_4>=0 & p5_14_4~=.);
replace valseg = valseg +p5_14_5 if ((p5_13_5==2| p5_13_5==3) & p5_14_5>=0 & p5_14_5~=.);
replace valseg = valseg +p5_14_6 if ((p5_13_6==2| p5_13_6==3) & p5_14_6>=0 & p5_14_6~=.);


rename valseg vlifeinsur;
label var vlifeinsur "value of the unit-linked or mixed life insurance";

*PLANES DE PENSIONES INCLUYENDO SEGUROS DE VIDA DE INVERSION O MIXTOS;
*PENSION SCHEMES INCLUDING UNIT-LINKED OR MIXED LIFE INSURANCE;

gen valpenseg=vpenplan+vlifeinsur;
rename valpenseg vpeninsur;
label var vpeninsur "value of pension schemes plus unit-linked or mixed life insurance";

*OTROS ACTIVOS FINANCIEROS;
*Para calcular el valor de la mediana de lo que se debe al hogar, utilizamos las variables valdeuhog y p4_38 y generamos una nueva variable;

*OTHER FINANCIAL ASSETS;
*To obtain the median of how much is owed to the household, we use the variables valdeuhog and p4_38 and generate a new variable; 

gen odeuhog=0;

replace odeuhog = odeuhog +valdeuhog if (valdeuhog>0);
replace odeuhog = odeuhog +p4_38 if (p4_38>0 & p4_38~=.);

rename odeuhog vcreditor;
label var vcreditor "how much is owed to the household";

*CUADRO 7: PROPORCION DE HOGARES Y MEDIANA DEL VALOR DE LOS DISTINTOS TIPOS DE DEUDA PENDIENTES;
*TABLE 7: PERCENTAGE OF HOUSEHOLDS AND VALUE’S MEDIAN OF THE DIFFERENT TYPES OF OUTSTANDING DEBT;

*DEUDAS  CLASIFICADAS POR TIPO DE ACTIVO INMOBILIARIO (TODO TIPO DE PRESTAMOS);
*DEBT CLASSIFIED BY TYPE OF REAL ESTATE ASSET (ALL KIND OF LOANS);

*VIVIENDA PRINCIPAL;
*MAIN RESIDENCE;

*Para calcular la proporción de hogares que tienen deudas pendientes de préstamos solicitados para la adquisición de la vivienda principal, utilizamos p2_8;
*To obtain the percentage of households that have outstanding debt from loans used to purchase their main residence, we generate a new variable;

gen np2_8=p2_8;
replace np2_8=0 if p2_8==.;

rename np2_8 debtmresid;
label var debtmresid "have outstanding debt from loans used to purchase main residence";

*Para calcular el valor de las deudas pendientes de préstamos solicitados para la adquisición de la vivienda principal, generamos una nueva variable;
*To obtain the value of the outstanding debts from loans used to purchase their main residence, we generate a new variable;

gen dvivpral=0;

replace dvivpral= dvivpral +p2_12_1 if  (p2_8a>=1 & p2_8a~=. & p2_12_1>0 & p2_12_1~=.);

replace dvivpral= dvivpral + p2_12_2 if (p2_8a>=2 & p2_8a~=. &  p2_12_2>0 & p2_12_2~=.);

replace dvivpral= dvivpral +p2_12_3  if (p2_8a>=3 & p2_8a~=. & p2_12_3>0 & p2_12_3~=.);

replace dvivpral= dvivpral +p2_12_4  if (p2_8a>3 & p2_8a~=. & p2_12_4>0 & p2_12_4~=.);

rename dvivpral vdebtmresid;
label var vdebtmresid "value of outstanding debts from loans used to purchase main residence";

*OTRAS PROPIEDADES INMOBILIARIAS DIFERENTES DE LA VIVIENDA PRINCIPAL;
*OTHER REAL ESTATE PROPERTIES DIFFERENT FROM THE MAIN RESIDENCE;

*Para calcular la proporción de hogares que tienen deudas pendientes de préstamos solicitados para la adquisición de otras propiedades inmobiliarias diferentes de la vivienda principal, generamos una nueva variable;

*To obtain the percentage of households that have outstanding debts from loans used to purchase other real estate properties different from the main 
*residence, we generate a new variable;

gen dpdte=(p2_50_1==1|p2_50_2==1|p2_50_3==1|p2_50_4==1);
rename dpdte debtothprop;
label var debtothprop "have outstanding debts from loans used to purchase other real estate properties";

*Para calcular el valor de las deudas pendientes de préstamos solicitados para la adquisición de otras propiedades inmobiliarias diferentes de la vivienda principal, generamos cuatro nuevas variables;

*To obtain the value of the outstanding debts from loans used to purchase other real estate properties different from the main residence, we generate
* four new variables;

*PARA LA PRIMERA PROPIEDAD INMOBILIARIA;
*FOR THE FIRST REAL ESTATE PROPERTY;

gen dprop1=0;

replace dprop1= dprop1+p2_55_1_1 if (p2_51_1>=1 & p2_51_1~=.  &  p2_55_1_1>0 & p2_55_1_1~=.);

replace dprop1= dprop1+ p2_55_1_2 if (p2_51_1>=2 & p2_51_1~=.  & p2_55_1_2>0 & p2_55_1_2~=.);

replace dprop1= dprop1+p2_55_1_3  if (p2_51_1>=3 & p2_51_1~=.  & p2_55_1_3>0 & p2_55_1_3~=.);


*PARA LA SEGUNDA PROPIEDAD INMOBILIARIA;
*FOR THE SECOND REAL ESTATE PROPERTY;

gen dprop2=0;

replace dprop2= dprop2+p2_55_2_1 if (p2_51_2>=1 & p2_51_2~=. & p2_55_2_1>0 & p2_55_2_1~=.);

replace dprop2= dprop2+ p2_55_2_2 if (p2_51_2>=2 & p2_51_2~=. & p2_55_2_2>0 & p2_55_2_2~=.);

replace dprop2= dprop2+ p2_55_2_3  if (p2_51_2>=3 & p2_51_2~=. & p2_55_2_3>0 & p2_55_2_3~=.);


*PARA LA TERCERA PROPIEDAD INMOBILIARIA;
*FOR THE THIRD REAL ESTATE PROPERTY;

gen dprop3=0;

replace dprop3= dprop3+p2_55_3_1 if (p2_51_3>=1 & p2_51_3~=. & p2_55_3_1>0 & p2_55_3_1~=.);

replace dprop3= dprop3+ p2_55_3_2 if (p2_51_3>=2 & p2_51_3~=. & p2_55_3_2>0 & p2_55_3_2~=.);

replace dprop3= dprop3+ p2_55_3_3  if (p2_51_3>=3 & p2_51_3~=. & p2_55_3_3>0 & p2_55_3_3~=.);


*PARA EL RESTO DE PROPIEDADES INMOBILIARIAS CUANDO HAY MAS DE TRES;
*FOR THE REST OF REAL ESTATE PROPERTIES WHEN THESE ARE MORE THAN THREE;

gen dprop4=0;

replace dprop4= dprop4+p2_55_4 if (p2_55_4>0 & p2_55_4~=.);

forvalues i=1(1)4{;
rename dprop`i' vdebtprop`i';
};

label var vdebtprop1 "value of the outstanding debts from loans used to purchase other real estate property #1";
label var vdebtprop2 "value of the outstanding debts from loans used to purchase other real estate property #2";
label var vdebtprop3 "value of the outstanding debts from loans used to purchase other real estate property #3";
label var vdebtprop4 "value of the outstanding debts from loans used to purchase other real estate properties #4";


*CONSIDERANDO CONJUNTAMENTE TODAS LAS PROPIEDADES INMOBILIARIAS DIFERENTES DE LA VIVIENDA PRINCIPAL;
*CONSIDERING ALL REAL ESTATE PROPERTIES DIFFERENT FROM THE MAIN RESIDENCE;

gen deuoprop= vdebtprop1+ vdebtprop2+ vdebtprop3+ vdebtprop4 ; 
rename deuoprop vdebtothprop;
label var vdebtothprop "value of the outstanding debts from loans used to purchase other real estate properties";

*DEUDAS PENDIENTES DE PRESTAMOS SOLICITADOS PARA LA ADQUISICION DE LA VIVIENDA PRINCIPAL CON GARANTIA HIPOTECARIA;
*OUTSTANDING DEBTS FROM LOANS WITH MORTGAGE GUARANTEE USED FOR THE PURCHASE OF THE MAIN RESIDENCE;

*Para calcular la proporción de hogares que tienen deudas pendientes de préstamos CON garantía hipotecaria solicitados para la adquisición de la vivienda principal, generamos una nueva variable;
*To obtain the percentage of households that have outstanding debts from loans with mortgage guarantee used for the purchase of the main residence, 
* we generate a new variable;

gen dpdtehipo = (p2_9_1==1|p2_9_2==1|p2_9_3==1|p2_9_4==1);
rename dpdtehipo mortgmresid;
label var mortgmresid " have mortgage for the purchase of the main residence";

*Para calcular el valor de las deudas pendientes de préstamos CON garantía hipotecaria solicitados para la adquisición de la vivienda principal, generamos una nueva variable;
*To obtain the value of the outstanding debts from loans with mortgage guarantee used for the purchase of the main residence, we generate a new variable;

gen deuhipv =0;

replace deuhipv= deuhipv + p2_12_1 if (p2_8a>=1 & p2_8a~=. & p2_9_1==1 & p2_12_1>0 & p2_12_1~=.);

replace deuhipv = deuhipv + p2_12_2 if (p2_8a>=2 & p2_8a~=. & p2_9_2==1 &  p2_12_2>0 & p2_12_2~=.);

replace deuhipv= deuhipv +p2_12_3  if (p2_8a>=3 & p2_8a~=. & p2_9_3==1 &  p2_12_3>0 & p2_12_3~=.);

replace deuhipv= deuhipv +p2_12_4  if (p2_8a>3 & p2_8a~=. & p2_8a~=. & p2_9_4==1 &  p2_12_4>0 & p2_12_4~=.);

rename deuhipv vmortgmresid;
label var vmortgmresid "value of outstanding mortgages for the purchase of the main residence";


*OTRAS DEUDAS PENDIENTES NO ASOCIADAS A LA ADQUISICION DE ACTIVOS INMOBILIARIOS;
*OTHER OUTSTANDING DEBT NOT RELATED TO THE PURCHASE OF REAL ESTATE ASSETS;

*DEUDAS PENDIENTES DE PRESTAMOS HIPOTECARIOS Y OTROS PRESTAMOS CON GARANTIA REAL;
*OUTSTANDING DEBTS FROM MORTGAGES AND OTHER SECURED LOANS);

*Para calcular la proporción de hogares que tienen deudas pendientes por prestamos hipotecarios y otros préstamos con garantía real generamos una nueva variable;
*To obtain the percentage of households that have outstanding debts from mortgages and other secured loans we generate a new variable;

gen hipo=(p3_2_1==1| p3_2_2==1| p3_2_3==1| p3_2_4==1|p3_2_5==1| p3_2_6==1| p3_2_7==1| p3_2_8==1|
p3_2_1==2| p3_2_2==2| p3_2_3==2| p3_2_4==2|p3_2_4==2|p3_2_5==2| p3_2_6==2| p3_2_7==2| p3_2_8==2|
p3_2_1==10| p3_2_2==10| p3_2_3==10| p3_2_4==10|p3_2_5==10| p3_2_6==10| p3_2_7==10| p3_2_8==10);


rename hipo mortgoth;
label var mortgoth "have mortgage for other porpuses";

*Para calcular el valor de las deudas pendientes por prestamos hipotecarios y otros préstamos con garantía real generamos una nueva variable;
*To obtain the value of the outstanding debts from mortgages and other loans with real guarantee we generate a new variable;

gen phipo=0;

replace phipo = phipo +p3_6_1 if ((p3_2_1==1|p3_2_1==2) & p3_6_1>0 & p3_6_1~=.);

replace phipo = phipo +p3_6_2 if ((p3_2_2==1| p3_2_2==2) & p3_6_2>0 & p3_6_2~=.);

replace phipo = phipo +p3_6_3 if ((p3_2_3==1| p3_2_3==2)  & p3_6_3>0 & p3_6_3~=.);

replace phipo = phipo +p3_6_4 if ((p3_2_4==1| p3_2_4==2) & p3_6_4>0 & p3_6_4~=.);

replace phipo = phipo +p3_6_5 if ((p3_2_5==1| p3_2_5==2) & p3_6_5>0 & p3_6_5~=.);

replace phipo = phipo +p3_6_6 if ((p3_2_6==1| p3_2_6==2) & p3_6_6>0 & p3_6_6~=.);

replace phipo = phipo +p3_6_7 if ((p3_2_7==1| p3_2_7==2) & p3_6_7>0 & p3_6_7~=.);

replace phipo = phipo +p3_6_8 if ((p3_2_8==1| p3_2_8==2) & p3_6_8>0 & p3_6_8~=.);

rename phipo vmortgoth;
label var vmortgoth "value of outstanding mortgages for other purposes";

*Variable capturing any kind of mortgage or secure debt ;
gen mortgage =0;
replace mortgage=1 if mortgoth==1 | mortgmresid==1;

*DEUDAS PENDIENTES DE PRESTAMOS PERSONALES;
*OUTSTANDING DEBTS FROM PERSONAL LOANS;

*Para calcular la proporción de hogares que tienen deudas pendientes por prestamos personales generamos una nueva variable;
*To obtain the percentage of households that have outstanding debts from personal loans we generate a new variable;

gen perso=(p3_2_1==3| p3_2_2==3| p3_2_3==3| p3_2_4==3|p3_2_5==3| p3_2_6==3| p3_2_7==3| p3_2_8==3);
rename perso personal;
label var personal "have outstanding debts from personal loans";

*Para calcular el valor de las deudas pendientes por prestamos personales generamos una nueva variable;
*To obtain the value of the outstanding debts from personal loans we generate a new variable;

gen pperso=0;

replace pperso = pperso +p3_6_1 if (p3_2_1==3 & p3_6_1>0 & p3_6_1~=.);
replace pperso = pperso +p3_6_2 if (p3_2_2==3 & p3_6_2>0 & p3_6_2~=.);
replace pperso = pperso +p3_6_3 if (p3_2_3==3 & p3_6_3>0 & p3_6_3~=.);
replace pperso = pperso +p3_6_4 if (p3_2_4==3 & p3_6_4>0 & p3_6_4~=.);
replace pperso = pperso +p3_6_5 if (p3_2_5==3 & p3_6_5>0 & p3_6_5~=.);
replace pperso = pperso +p3_6_6 if (p3_2_6==3 & p3_6_6>0 & p3_6_6~=.);
replace pperso = pperso +p3_6_7 if (p3_2_7==3 & p3_6_7>0 & p3_6_7~=.);
replace pperso = pperso +p3_6_8 if (p3_2_8==3 & p3_6_8>0 & p3_6_8~=.);

rename pperso vpersonal;
label var vpersonal "value of personal loans";


*DEUDAS PENDIENTES CON TARJETAS DE CREDITO;
*OUTSTANDING CREDIT CARD BALANCES;

*Para calcular la proporción de hogares que tienen deudas pendientes con tarjetas de credito generamos una nueva variable;
*To obtain the percentage of households that have outstanding credit card balances we generate a new variable;

gen deuda_tarj=(p8_5a>0 & p8_5a~=.);
rename deuda_tarj credcard;
label var credcard "have outstanding credit card balances";

*Para calcular el valor de las deudas pendientes con tarjetas de credito generamos una nueva variable;
*To obtain the value of outstanding credit card balances we generate a new variable;

gen ptmos_tarj=0;

replace ptmos_tarj= p8_5a if (p8_5a>0 & p8_5a~=.);
rename ptmos_tarj vcredcard;
label var vcredcard "value of outstanding credit card balances";



*OTRAS DEUDAS;
*OTHER DEBTS;

*Para calcular la proporción de hogares que tienen otras deudas pendientes generamos una nueva variable;
*To obtain the percentage of households that have other outstanding debts we generate a new variable;

gen otrasd=(p3_2_1==4| p3_2_2==4| p3_2_3==4| p3_2_4==4| p3_2_5==4| p3_2_6==4| p3_2_7==4| p3_2_8==4|p3_2_1==5| p3_2_2==5| p3_2_3==5| p3_2_4==5| p3_2_5==5|
 p3_2_6==5| p3_2_7==5| p3_2_8==5| p3_2_1==6| p3_2_2==6| p3_2_3==6| p3_2_4==6| p3_2_5==6| p3_2_6==6| p3_2_7==6| p3_2_8==6| p3_2_1==7| p3_2_2==7| p3_2_3==7|
 p3_2_4==7| p3_2_5==7| p3_2_6==7| p3_2_7==7| p3_2_8==7| p3_2_1==8| p3_2_2==8| p3_2_3==8| p3_2_4==8| p3_2_5==8| p3_2_6==8| p3_2_7==8| p3_2_8==8| p3_2_1==9|
 p3_2_2==9| p3_2_3==9| p3_2_4==9| p3_2_5==9| p3_2_6==9| p3_2_7==9| p3_2_8==9| p3_2_1==97| p3_2_2==97| p3_2_3==97| p3_2_4==97 | p3_2_5==97| p3_2_6==97| 
 p3_2_7==97| p3_2_8==97);
rename otrasd othdebt;
label var othdebt "households that have other outstanding debt";


*Para calcular el valor de las otras deudas pendientes generamos una nueva variable;
*To obtain the value of the other outstanding debts we generate a new variable;

gen potrasd =0;

replace potrasd = potrasd +p3_6_1 if ((p3_2_1==4| p3_2_1==5| p3_2_1==6| p3_2_1==7| p3_2_1==8|p3_2_1==9|
p3_2_1==97) & p3_6_1>0 & p3_6_1~=.);
replace potrasd = potrasd +p3_6_2 if ((p3_2_2==4| p3_2_2==5|  p3_2_2==6| p3_2_2==7| p3_2_2==8|p3_2_2==9|
p3_2_2==97) & p3_6_2>0 & p3_6_2~=.);
replace potrasd = potrasd +p3_6_3 if ((p3_2_3==4| p3_2_3==5| p3_2_3==6| p3_2_3==7| p3_2_3==8|p3_2_3==9|
p3_2_3==97) & p3_6_3>0 & p3_6_3~=.);
replace potrasd = potrasd +p3_6_4 if ((p3_2_4==4| p3_2_4==5| p3_2_4==6| p3_2_4==7| p3_2_4==8|p3_2_4==9|
p3_2_4==97) & p3_6_4>0 & p3_6_4~=.);
replace potrasd = potrasd +p3_6_5 if ((p3_2_5==4| p3_2_5==5| p3_2_5==6| p3_2_5==7| p3_2_5==8|p3_2_5==9|
p3_2_5==97) & p3_6_5>0 & p3_6_5~=.);
replace potrasd = potrasd +p3_6_6 if ((p3_2_6==4| p3_2_6==5| p3_2_6==6| p3_2_6==7| p3_2_6==8|p3_2_6==9|
p3_2_6==97) & p3_6_6>0 & p3_6_6~=.);
replace potrasd = potrasd +p3_6_7 if ((p3_2_7==4| p3_2_7==5| p3_2_7==6| p3_2_7==7| p3_2_7==8|p3_2_7==9|
p3_2_7==97) & p3_6_7>0 & p3_6_7~=.);
replace potrasd = potrasd +p3_6_8 if ((p3_2_8==4| p3_2_8==5| p3_2_8==6| p3_2_8==7| p3_2_8==8|p3_2_8==9|
p3_2_8==97) & p3_6_8>0 & p3_6_8~=.);

rename potrasd vothdebt;
label var vothdebt "value of the other outstanding debts";



******************************************************************************************************;
******************************************************************************************************;

*                          R A N K I N G     A: NATURE OF THE DEBT									 *;

******************************************************************************************************;
******************************************************************************************************;
gen housesec=0;
gen houseunsec=0;
gen othsecured=0;
gen consumer=0;
gen rest=0;

gen vhousesec=0;
gen vhouseunsec=0;
gen vothsecured=0;
gen vconsumer=0;
gen vrest=0;

replace vhousesec=vhousesec+p2_55_4 if p2_55_4!=. /*Consider as secured, all debts attached to fourth real state properties in advanced */;

forvalues i=1(1)4 {;
replace housesec=1 if p2_9_`i'<=2;
replace vhousesec=vhousesec+p2_12_`i' if p2_9_`i'<=2; 
replace houseunsec=1 if p2_9_`i'>2 & p2_9_`i'<=97;
replace vhouseunsec=vhouseunsec+p2_12_`i' if p2_9_`i'>2 & p2_9_`i'<=97;
};

forvalues i=1(1)3 {;
		forvalues s=1(1)3 {; 
		replace housesec=1 if p2_52_`i'_`s'<=2;
		replace vhousesec=vhousesec+p2_55_`i'_`s' if  p2_52_`i'_`s'<=2;
		replace houseunsec=1 if p2_52_`i'_`s'>2 & p2_52_`i'_`s'<=97;
		replace vhouseunsec=vhousesec+p2_55_`i'_`s' if  p2_52_`i'_`s'>2 & p2_52_`i'_`s'<=97;
};
};

forvalues i=1(1)8 {;
replace othsecured=1 if p3_2_`i'<=2;
replace vothsecured=vothsecured+p3_6_`i' if p3_2_`i'<=2;
replace consumer=1 if p3_2_`i'==3;
replace vconsumer=vconsumer+p3_6_`i' if p3_2_`i'==3;
replace rest=1 if p3_2_`i'>3 & p3_2_`i'<=97;
replace vrest=vrest+p3_6_`i' if p3_2_`i'>3 & p3_2_`i'<=97;

};
******************************************************************************************************;
******************************************************************************************************;

*                          R A N K I N G     B: OBJECIVE OF THE DEBT									 *;

******************************************************************************************************;
******************************************************************************************************;

gen housing=0;
*gen carloan=0;
gen busloan=0;
gen restbis=0;

replace housing=1 if housesec==1;
replace restbis=1 if houseunsec==1;
forvalues i=1(1)8 {;
*replace carloan=1 if p3_3_`i'==2;
replace busloan=1 if p3_3_`i'==12;
replace housing=1 if p3_3_`i'==14 & p3_2_`i'<=2;
replace restbis=1 if p3_3_`i'==1 | p3_3_`i'==2 | p3_3_`i'==3 | p3_3_`i'==4 | p3_3_`i'==34 | p3_3_`i'==5 | p3_3_`i'==6 | p3_3_`i'==7 | p3_3_`i'==8 | p3_3_`i'==9 |
						p3_3_`i'==10 | p3_3_`i'==11 | p3_3_`i'==13 | (p3_3_`i'==14 & p3_2_`i'>2) | p3_3_`i'==15 | p3_3_`i'==97;
};

gen vhousing=0;
*gen vcarloan=0;
gen vbusloan=0;
gen vrestbis=0;

replace vhousing=vhousesec;
replace vrestbis=vhouseunsec;
forvalues i=1(1)8 {;
*replace vcarloan=vcarloan + p3_6_`i' if p3_3_`i'==2;
replace vbusloan=vbusloan + p3_6_`i'  if p3_3_`i'==12;
replace vhousing=vhousing + p3_6_`i' if p3_3_`i'==14 & p3_2_`i'<=2;
replace vrestbis=vrestbis + p3_6_`i' if p3_3_`i'==1 | p3_3_`i'==2 | p3_3_`i'==3 | p3_3_`i'==4 | p3_3_`i'==34 | p3_3_`i'==5 | p3_3_`i'==6 | p3_3_`i'==7 | p3_3_`i'==8 | p3_3_`i'==9 |
						p3_3_`i'==10 | p3_3_`i'==11 | p3_3_`i'==13 | (p3_3_`i'==14 & p3_2_`i'>2) | p3_3_`i'==15 | p3_3_`i'==97;;
};

foreach var in vhousing vbusloan vcredcard vrestbis {;
replace `var'=`var'/acpi*100;
};

 ******************* INTEREST RATES *************************;
* Main residence;
forvalues i=1(1)4{;
*rename p2_9_`i' loantypemresid_`i' /* 1-mortgage, 2- othsecured, 3- personal, 4- credit line, 5- deferred, 6- advances, 7- friends family, 97- other, 98- don't know missing */;
rename p2_13_`i' loanratemresid_`i';
rename p2_14_`i' loanfixmresid_`i';
replace loanfixmresid_`i'=1 if loanfixmresid_`i'==22;
replace loanfixmresid_`i'=0 if loanfixmresid_`i'==11;
};

* Other properties (up to 3 additional properties and 3 loans for each one);
forvalues a=1(1)3{ /*property*/;
forvalues i=1(1)3{ /*loan*/;

*rename p2_52_`a'_`i' loantypeothprop_`a'_`i' /* 1-mortgage, 2- othsecured, 3- personal, 4- credit line, 5- deferred, 6- advances, 7- friends family, 97- other, 98- don't know missing */;
rename p2_56_`a'_`i' loanrateothprop_`a'_`i';
rename p2_57_`a'_`i' loanfixothprop_`a'_`i';
replace loanfixothprop_`a'_`i'=1 if loanfixothprop_`a'_`i'==22;
replace loanfixothprop_`a'_`i'=0 if loanfixothprop_`a'_`i'==11;
};
};


* Other loans;
forvalues i=1(1)8{;
*rename p3_2_`i' loantypeother_`i' /* 1-mortgage, 2- othsecured, 3- personal, 4- credit line, 5- deferred, 6- advances, 7- friends family, 97- other, 98- don't know missing */;
rename p3_7_`i' loanrateother_`i';
rename p3_8_`i' loanfixother_`i';
replace loanfixother_`i'=1 if loanfixother_`i'==22;
replace loanfixother_`i'=0 if loanfixother_`i'==11;
};

* Credit card;
rename p8_5c int_credcard;


*************************** INTEREST RATES *******************************;
******* Housing ********;
gen int_housing=0;
forvalues i=1(1)4{;
replace int_housing=int_housing+loanratemresid_`i'*p2_12_`i' if p2_9_`i'<=2; 
};

forvalues a=1(1)3 {;
forvalues i=1(1)3 {;
replace int_housing=int_housing+loanrateothprop_`a'_`i'*p2_55_`a'_`i' if  p2_52_`a'_`i'<=2;
};
};

forvalues i=1(1)8{;
replace int_housing=int_housing+loanrateother_`i'*p3_6_`i' if p3_3_`i'==14 & p3_2_`i'<=2;
};
replace p2_55_4=0 if p2_55_4==.;
replace int_housing=int_housing/(vhousing-p2_55_4);

******** Business *******;
gen int_busloan=0;
forvalues i=1(1)8{;
replace int_busloan=int_busloan+loanrateother_`i'*p3_6_`i' if p3_3_`i'==12;
};

replace int_busloan=int_busloan/vbusloan;

********* Other *********;
gen int_restbis=0;
forvalues i=1(1)4{;
replace int_restbis=int_restbis+loanratemresid_`i'*p2_12_`i' if p2_9_`i'>2 & p2_9_`i'<=97; 
};

forvalues a=1(1)3 {;
forvalues i=1(1)3 {;
replace int_restbis=int_restbis+loanrateothprop_`a'_`i'*p2_55_`a'_`i' if  p2_52_`a'_`i'>2 & p2_52_`a'_`i'<=97;
};
};

forvalues i=1(1)8{;
replace int_restbis=int_restbis+loanrateother_`i'*p3_6_`i'  if p3_3_`i'==1 | p3_3_`i'==2 | p3_3_`i'==3 | p3_3_`i'==4 | p3_3_`i'==34 | p3_3_`i'==5 | p3_3_`i'==6 | p3_3_`i'==7 | p3_3_`i'==8 | p3_3_`i'==9 |
						p3_3_`i'==10 | p3_3_`i'==11 | p3_3_`i'==13 | (p3_3_`i'==14 & p3_2_`i'>2) | p3_3_`i'==15 | p3_3_`i'==97;
};

replace int_restbis=int_restbis/vrestbis;
*************** Debt Portfolio Structure ***************;
/* Housing (debt 1), busloan (portfdebt2), Credcard (debt 3), Rest (debt 4)*/; 


******* ONE DEBT ********************************************************************;
gen portfdebt1=0;
replace portfdebt1=1 if housing==1 & busloan==0 & credcard==0 & restbis==0;

gen portfdebt2=0;
replace portfdebt2=1 if housing==0 & busloan==1 & credcard==0 & restbis==0;

					
gen portfdebt3=0;
replace portfdebt3=1 if housing==0 & busloan==0 & credcard==1 & restbis==0;

gen portfdebt4=0;
replace portfdebt4=1 if housing==0 & busloan==0 & credcard==0 & restbis==1;


******* TWO DEBTS ********************************************************************;
gen portfdebt12=0;
replace portfdebt12=1 if housing==1 & busloan==1 & credcard==0 & restbis==0;

gen portfdebt13=0;
replace portfdebt13=1 if housing==1 & busloan==0 & credcard==1 & restbis==0;

gen portfdebt14=0;
replace portfdebt14=1  if housing==1 & busloan==0 & credcard==0 & restbis==1;

gen portfdebt23=0;
replace portfdebt23=1  if housing==0 & busloan==1 & credcard==1 & restbis==0;

gen portfdebt24=0;
replace portfdebt24=1  if housing==0 & busloan==1 & credcard==0 & restbis==1;


gen portfdebt34=0;
replace portfdebt34=1  if housing==0 & busloan==0 & credcard==1 & restbis==1;


**********THREE DEBTS ********************************************************************;
gen portfdebt123=0;
replace portfdebt123=1  if housing==1 & busloan==1 & credcard==1 & restbis==0;

gen portfdebt124=0;
replace portfdebt124=1  if housing==1 & busloan==1 & credcard==0 & restbis==1;

gen portfdebt134=0;
replace portfdebt134=1  if housing==1 & busloan==0 & credcard==1 & restbis==1;

gen portfdebt234=0;
replace portfdebt234=1  if housing==0 & busloan==1 & credcard==1 & restbis==1;

********* FOUR DEBTS *********************************************************************;
gen portfdebt1234=0;
replace portfdebt1234=1  if housing==1 & busloan==1 & credcard==1 & restbis==1;
******************************************************************************************************;



*ALGUN TIPO DE DEUDA PENDIENTE;
*SOME TYPE OF OUTSTANDING DEBT;

*Para calcular la proporción de hogares que tienen algún tipo de deuda pendiente generamos una nueva variable;
*To obtain the percentage of households that have some type of outstanding debt we generate a new variable;

gen adeuda= (debtmresid==1| debtothprop==1| p3_1>0 | credcard==1);
rename adeuda anydebt;
label var anydebt "have some type of outstanding debt";

*Para calcular el valor de las deudas pendientes generamos una nueva variable;
*To obtain the value of the outstanding debt we generate a new variable;

gen vdeuda= vdebtmresid + vdebtothprop+ vmortgoth+ vpersonal+ vothdebt + vcredcard;
rename vdeuda vdebt;
label var vdebt "value of the outstanding debt";

foreach var in portfdebt1 portfdebt2 portfdebt3 portfdebt4 portfdebt12 portfdebt13 portfdebt14 portfdebt23 
 portfdebt24 portfdebt34 portfdebt123 portfdebt124 portfdebt134 portfdebt234 portfdebt1234 {;
 
 gen v`var'=.;
 replace v`var'=vdebt if `var'==1;
 
 };

*VARIABLES DE RIQUEZA TOTAL Y RIQUEZAS INTERMEDIAS;
*TOTAL AND INTERMEDIATE WEALTH VARIABLES;


*ACTIVOS REALES;
*REAL ASSETS;

gen actreales=0;
replace actreales=actreales+vmresid if (vmresid>0 & vmresid~=.);
replace actreales=actreales+vothprop if (vothprop>0 & vothprop~=.);
replace actreales=actreales+vjewel if (vjewel>0 & vjewel~=.);
replace actreales=actreales+valhog if (valhog>0 & valhog~=.);

rename actreales rassets;
label var rassets "Value of real assets";


*ACTIVOS FINANCIEROS;
*FINANCIAL ASSETS;

gen actfinanc=0;
replace actfinanc=actfinanc+vaccount_pay if (vaccount_pay>0 & vaccount_pay~=.);
replace actfinanc=actfinanc+vlistshare if (vlistshare>0 & vlistshare~=.);
replace actfinanc=actfinanc+vunlist if (vunlist>0 & vunlist~=.);
replace actfinanc=actfinanc+vfixsec if (vfixsec>0 & vfixsec~=.);
replace actfinanc=actfinanc+allf if (allf>0 & allf~=.);
replace actfinanc=actfinanc+p4_43 if (p4_43>0 & p4_43~=.) /* Carteras gestionadas*/;
replace actfinanc=actfinanc+vaccount_nopay if (vaccount_nopay>0 & vaccount_nopay~=.);
replace actfinanc=actfinanc+vpenplan if (vpenplan>0 & vpenplan~=.);
replace actfinanc=actfinanc+vlifeinsur if (vlifeinsur>0 & vlifeinsur~=.);
replace actfinanc=actfinanc+vcreditor if (vcreditor>0 & vcreditor~=.);


rename actfinanc fassets;
label var fassets "Value of financial assets";

*RIQUEZA BRUTA;
*GROSS WEALTH;

gen riquezabr=0;
replace riquezabr=riquezabr+rassets+fassets;

rename riquezabr gwealth;
label var gwealth "Gross Wealth";

*RIQUEZA NETA=RIQUEZA BRUTA-DEUDAS;
*NET WEALTH=GROSS WEALTH-DEBTS;

gen riquezanet=gwealth-vdebt;
rename riquezanet nwealth;
label var nwealth "Net Wealth";

*CUADRO 6: VALOR TIPOS DE DEUDA SEGUN OBJETIVO DE LA DEUDA;
*TABLE 6: VALUE OF DEBTS BY PURPOSE OF DEBTS;

*TBD;

*Para deuda por compra vivienda principal usamos dvivpral;
*For debt originated by home purchase we use dvivpral;

*Para deuda por compra otras prop. inmobiliarias usamos deuoprop;
*For debt originated by purchase of other real estate properties we use deuoprop;

*Para deudas pendientes por el resto de deudas (garantia real, credito personal, otras deudas, deudas con tarjetas de credito) usaremos deuotros;
*For other outstanding debts (secured loans, personal loans, credit card balances and other debts) we use deuotros;

*CUADRO 8: RATIOS INDIVIDUALES DE DEUDA;
*TABLE 8: INDIVIDUAL DEBT RATIOS;

*PAGOS POR DEUDAS;
*DEBT PAYMENTS;

*Para el total de pagos por deudas generamos la variable pagodeuda;
*For total debt payments we generate the variable pagodeuda;

gen pagodeuda=0;
gen pagodeuviv=0;
gen pagodeuoprop=0;
gen pagodeusec3=0;
set output error;
forvalues j=1/4 {;
	display _newline(1) `j';
	gen np2_18_`j'=p2_18_`j';
	replace np2_18_`j'=0 if (p2_18_`j'==.|p2_18_`j'<0);
	replace pagodeuviv=pagodeuviv+np2_18_`j';
			};

forvalues j=1/8 {;
	display _newline(1) `j';
	gen np3_11_`j'=p3_11_`j';
	replace np3_11_`j'=0 if (p3_11_`j'==.|p3_11_`j'<0);
	replace pagodeusec3=pagodeusec3+np3_11_`j';
			};

forvalues m=1/3   {;
	forvalues j=1/3 {;
	display _newline(1) `m' `j';
		gen np2_61_`m'_`j'=p2_61_`m'_`j';
	replace np2_61_`m'_`j'=0 if (p2_61_`m'_`j'==.|p2_61_`m'_`j'<0);
	replace pagodeuoprop=pagodeuoprop+np2_61_`m'_`j';
			};
};
set output proc;

gen np2_61_4=p2_61_4;
replace np2_61_4=0 if (p2_61_4==. | p2_61_4<0);
replace pagodeuoprop=pagodeuoprop+np2_61_4;

gen np8_5b=p8_5b;
replace np8_5b=0 if (p8_5b==. | p8_5b<0);
gen pagotarjeta=np8_5b;
	
replace pagodeuda=pagodeuviv+pagodeuoprop+pagodeusec3 + pagotarjeta;


rename pagodeuda paydebt;
label var paydebt "Monthly total debt payments";
rename pagodeuviv paydresid;
label var paydresid "Monthly residential debt payments";
rename pagodeuoprop payothprop;
label var payothprop "Monthly other properties debt payments";
rename pagodeusec3 paypersonal;
label var paypersonal "Monthly personal debt payments";

*CUADRO 9: GASTO EN BIENES DURADEROS Y NO DURADEROS Y TENENCIA DE BIENES DURADEROS;
*TABLE 9: EXPENDITURE ON NON-DURABLE AND DURABLE GOODS AND HOLDINGS OF DURABLE GOODS;

*1.-GASTO ANUAL BIENES VARIOS (% y mediana);
*1.-ANNUAL EXPENDITURE ON DIFFERENT GOODS (% and median);

*Gasto anual en Alimentacion;
*Annual expenditure on Food;

gen frec=12 if p9_2b==2;
replace frec=12*4.3 if p9_2b==1;
gen alim=0;
replace alim=alim+(p9_2*frec) if p9_2>0;
rename alim food;
label var food "Annual expenditure on Food";

*Gasto anual en Otros bienes no duraderos;
*Annual expenditure on Other non-durable goods;

gen nodur=0;
replace nodur=nodur+ (p9_1*12)-food if p9_1>0;
label var nodur "Annual expenditure on Other non-durable goods";

*Gasto anual en vehiculos (si/no y valor);
*Annual expenditure on vehicles (yes/no and value);

*Para decisión adquisición vehículos;
*For the decision to buy vehicles;

gen gvehic=(p2_73==1 | p2_77==1);
rename gvehic vehic;
label var vehic "household purchased a vehicle that year";

*Para valor adquisicion vehículos;
*For the value of vehicles purchased;

gen gimpvehic=0;
replace gimpvehic=gimpvehic+p2_74 if (p2_74>0 & p2_74~=.);
replace gimpvehic=gimpvehic+p2_78 if (p2_78>0 & p2_78~=.);
rename gimpvehic vvehicle;
label var vvehicle "value of vehicles purchased";

*Gasto anual en Otros bienes duraderos (si/no y valor);
*Annual expenditure on Other durable goods (yes/no and value);


*Para decisión adquisición bienes duraderos utilizamos la p2_69;
*For the decision to buy durable goods we use the variable p2_69;

*Para valor adquisicion bienes duraderos usamos p2_70;
*For the value of durable goods purchases we use p2_70;


*2.- PARA TENENCIA DURADEROS (% Y MEDIANA);
*2.- FOR HOLDINGS OF DURABLE GOODS (% AND MEDIAN);

*Tenencia vehiculos;
*Holding of vehicles;

*Proporcion con vehiculos;
*Percentage with vehicles;

gen tvehic=(p2_72>0|p2_76>0);

*Mediana para los que tienen;
*Median for the ones who have; 

gen timpvehic=0;
replace timpvehic = timpvehic + p2_75 if (p2_72>0 & p2_75>0 & p2_75~=.);
replace timpvehic = timpvehic + p2_79 if ( p2_76>0 &  p2_79>0 & p2_79~=.);

*Tenencia Otros bienes duraderos;
*Holding of Other durable goods;

*Para valor tenencia bienes duraderos usamos p2_71;
*For the value of durable goods holdings we use p2_71;


*VARIABLES DE CARACTERISTICAS DE LOS HOGARES QUE FIGURAN EN LOS CUADROS;
*VARIABLES OF HOUSEHOLD CHARACTERISTICS THAT APPEAR IN THE TABLES;

*1.- DEFINICIÓN DE PERCENTILES (i) RENTA TOTAL HOGAR Y (ii) RIQUEZA NETA;
*1.- DEFINITION OF PERCENTILES (i) HOUSEHOLD TOTAL INCOME AND (ii) NET WEALTH; 
rename renthog hhincome /* annual 2001 for 2002 wave, 2004 (2005 wave), 2007 (2008 wave) */;
_pctile hhincome [pweight=facine3], p(20,40,60,80,90);
return list;

gen percrent=1 if (hhincome<r(r1));
replace percrent=2 if (hhincome>=r(r1) & hhincome<r(r2));
replace percrent=3 if (hhincome>=r(r2) & hhincome<r(r3));
replace percrent=4 if (hhincome>=r(r3) & hhincome<r(r4));
replace percrent=5 if (hhincome>=r(r4) & hhincome<r(r5));
replace percrent=6 if  hhincome>=r(r5);


_pctile nwealth [pweight=facine3], p(25,50,75,90);
return list;

gen percriq=1 if (nwealth<r(r1));
replace percriq=2 if (nwealth>=r(r1) & nwealth<r(r2));
replace percriq=3 if (nwealth>=r(r2) & nwealth<r(r3));
replace percriq=4 if (nwealth>=r(r3) & nwealth<r(r4));
replace percriq=5 if  nwealth>=r(r4);

gen percriq25=1 if nwealth==r(r1);
gen percriq50=1 if nwealth==r(r2);
gen percriq75=1 if nwealth==r(r3);

foreach var in vhousing vbusloan vcredcard vrestbis {;
gen nwealth_`var'=nwealth +`var';

gen percriq_`var'25=1 if nwealth_`var'==r(r1);
gen percriq_`var'50=1 if nwealth_`var'==r(r2);
gen percriq_`var'75=1 if nwealth_`var'==r(r3);
};
*2.- NOMBRE Y CODIFICACIÓN DE LAS VARIABLES QUE RECOGEN CARACTERÍSTICAS SOCIO-DEMOGRÁFICAS DEL HOGAR QUE APARECEN EN LOS CUADROS;
*2.- NAME AND CODING OF THE VARIABLES THAT CONTAIN HOUSEHOLDS SOCIO-DEMOGRAPHIC CHARACTERISTICS THAT APPEAR IN THE TABLES;

*EDAD DEL CABEZA DE FAMILIA;
*AGE OF HOUSEHOLD HEAD;
*bage: toma valores 1 a 6, <35, >34 & <45, >44 & <55, >54 & <65, >64 & <75, >74;
*bage: takes values 1 to 6, <35, >34 & <45, >44 & <55, >54 & <65, >64 & <75, >74;

*SITUACION LABORAL DEL CABEZA DE FAMILIA;
*LABOUR MARKET SITUATION OF HOUSEHOLD HEAD;
*nsitlabdom: toma valores 1 a 4, empleado por cuenta ajena, empleado por cuenta propia, jubilado, otro tipo de inactivo o parado;
*nsitlabdom: takes values 1 to 4, employee, self-employed, retired, other type of economic inactivity or unemployed;

*NIVEL DE EDUCACION DEL CABEZA DE FAMILIA;
*LEVEL OF EDUCATION OF HOUSEHOLD HEAD;
*neducdom: toma valores 1 a 3, inferior a bachillerato, bachillerato, estudios universitarios;
*neducdom: takes values 1 to 3, below secondary education, secondary education, University education;

*REGIMEN DE TENENCIA DE LA VIVIENDA PRINCIPAL;
*STATUS OF MAIN RESIDENCE;
*np2_1: toma valores 1 y 0, propiedad, otros regímenes de tenencia;
*np2_1: takes values 1 and 0, ownership, other;


*NUMERO DE ADULTOS EN EL HOGAR TRABAJANDO;
*NUMBER OF ADULT HOUSEHOLD MEMBERS WORKING;
*nnumadtrab: toma valores 0 a 3, ninguno, uno, dos, tres o más;
*nnumadtrab: takes values 0 to 3, none, one, two, three or more;


*NUMERO DE MIEMBROS EN EL HOGAR;
*NUMBER OF HOUSEHOLD MEMBERS;
*np1: toma valores 1 a 5, uno, dos, tres, cuatro, cinco o más.
*np1: takes values 1 to 5, one, two, three, four, five or more.
	

**** Reference person (designed by the household) variables ****;
/* From questionnaire: "The reference person is the person, or one of the persons, responsible for the accommodation. It will normally be the person in the 
household who chiefly deals with the financial issues." */;

**** Reference person (designed by the household) variables ****;
/* From questionnaire: "The reference person is the person, or one of the persons, responsible for the accommodation. It will normally be the person in the 
household who chiefly deals with the financial issues." */;

rename p1 members /* Number of household members */;



forvalues i = 1(1)9 {;
	rename p1_1_`i' sex`i' /* Male (1), Female (0)*/;
	replace sex`i'=0 if sex`i'==2;
	rename p1_2b_`i' nac`i';
	rename p1_3_`i' relref`i';
	rename p1_5_`i' educ`i' /* Education level (see questionnaire)*/;
	rename p1_7_`i' health`i' /* Health status of reference person: 1-very good, 2-good, 3-acceptable, 4-poor, 5-very poor */;
	rename p6_1c1_`i' employee`i';
	rename p6_1c2_`i' selfemployed`i';
	rename p6_1c3_`i' unemployed`i';
	rename p6_1c4_`i' retiree`i';
	rename p6_1c5_`i' disable`i';
	rename p6_1c6_`i' student`i';
	rename p6_1c7_`i' housew`i';
	rename p6_1c8_`i' oth_inact`i';
	rename p6_4_`i' typejob`i';
	gen bankjob`i'=0;
	replace bankjob`i'=1 if typejob`i'==9;
	};

	
forvalues i = 1(1)9 {;
	gen ageaux`i'=0;
	replace ageaux`i'=2014-nac`i';
	gen child`i'=0;
	replace child`i'=1 if ageaux`i'<16 ;
	};

cap drop ageaux*;

egen nchilds=rowtotal(child1-child9);
	
gen sex=0;
gen nac=0;
gen educ=0;
gen health=0;
gen employee=0;
gen selfemployed=0;
gen unemployed=0;
gen retiree=0;
gen disable=0;
gen student=0;
gen housew=0;
gen oth_inact=0;
gen bankjob=0;

* Dummy variable for university degree;
* Ordinary university degree / Training leading to an officially recognised professional specialisation;
* Postgraduate university education ;

forvalues i = 1(1)9 {;
gen univ`i'=0;
replace univ`i'=1 if educ`i'==1001 | educ`i'==1002 | educ`i'==11 | educ`i'==12;
};

gen univ=0;

/* Marital status reference person: married if any other person in the household declares to be the couple of the head */;

gen married=0;

forvalues i = 2(1)9 {;
	replace married=1 if relref`i'==2;
	};

gen couplewith=(married==1 & nchilds>0);
gen couplewithout=(married==1 & nchilds==0);
gen singlewith=(married==0 & nchilds>0);
gen singlewithout=(married==0 & nchilds==0);	
	
rename p1_4_1 marital1 /* Marital status reference person: 1-single, 2-married, 3-de facto partner 
						4-separated, 5-divorced, 6-widowed */;

/* With the information of the other members, create variables that summarize the familiar characteristics */;

*gen othcoup=0 /* to identify those hh where household head is not the reference person in the survey */;

*CRITERIUM: Take the main earner in employees. Otherwise, take the male;

* Compute wage for each member of the household;
forvalues i=1(1)9{;
replace student`i'=0 if oth_inact`i'==1 | disable`i'==1 | housew`i'==1 | unemployed`i'==1 | retiree`i'==1 | selfemployed`i'==1 | employee`i'==1;
replace oth_inact`i'=0 if disable`i'==1 | housew`i'==1 | unemployed`i'==1 | retiree`i'==1 | selfemployed`i'==1 | employee`i'==1;
replace disable`i'=0 if housew`i'==1 | unemployed`i'==1 | retiree`i'==1 | selfemployed`i'==1 | employee`i'==1;
replace housew`i'=0 if unemployed`i'==1 | retiree`i'==1 | selfemployed`i'==1 | employee`i'==1;
replace unemployed`i'=0 if retiree`i'==1 | selfemployed`i'==1 | employee`i'==1;
replace retiree`i'=0 if selfemployed`i'==1 | employee`i'==1;
replace selfemployed`i'=0 if employee`i'==1;
gen ageaux`i'=0;
replace ageaux`i'=2014-nac`i';
replace retiree`i'=1 if (housew`i'==1 | oth_inact`i'==1 | disable`i'==1 | student`i'==1) & ageaux`i'>=65 /* Take this persons as retired */;
replace housew`i'=0 if retiree`i'==1;
replace oth_inact`i'=0 if retiree`i'==1;
replace disable`i'=0 if retiree`i'==1;
replace student`i'=0 if retiree`i'==1;
};

forvalues i=1(1)9{;
	egen wage`i'=rowtotal(p6_14_`i'_*);
	gen mainearner`i'=0;
		replace employee`i'=1 if wage`i'>0 & student`i'==0 & oth_inact`i'==0 & disable`i'==0 & housew`i'==0 & 
	unemployed`i'==0 & retiree`i'==0 & selfemployed`i'==0 & employee`i'==0;
	};
	
replace mainearner1=1;

forvalues i=2(1)9{;
	replace mainearner`i'=1 if wage`i'>wage1 & relref`i'==2 & employee`i'==1;
	replace mainearner1=0   if wage`i'>wage1 & relref`i'==2 & employee`i'==1;	
	};	

forvalues i =2(1)9 {;
	gen othcoup`i'=0;
	replace othcoup`i'=1 if married==1 & sex1==0 & sex`i'==1 & relref`i'==2;	
	replace othcoup`i'=1 if married==1 & mainearner`i'==1 & relref`i'==2;
	replace othcoup`i'=1 if married==1 & (housew==1 | student==1) & 
		(unemployed`i'==1 | retiree`i'==1 | selfemployed`i'==1) & relref`i'==2 /*Take the couple when head is housewife */;
	replace sex=sex`i' if othcoup`i'==1;
	replace nac=nac`i' if othcoup`i'==1;
	replace educ=educ`i' if othcoup`i'==1;
	replace health=health`i' if othcoup`i'==1;
	replace employee=employee`i' if othcoup`i'==1;
	replace selfemployed=selfemployed`i' if othcoup`i'==1;
	replace unemployed=unemployed`i' if othcoup`i'==1;
	replace student=student`i' if othcoup`i'==1;
	replace housew=housew`i' if othcoup`i'==1;
	replace oth_inact=oth_inact`i' if othcoup`i'==1;
	replace retiree=retiree`i' if othcoup`i'==1;
	replace health=health`i' if othcoup`i'==1;
	replace univ=univ`i' if othcoup`i'==1;
	replace bankjob=bankjob`i' if othcoup`i'==1;
	};

egen othcoup=rowtotal(othcoup*);

replace sex=sex1 if othcoup==0;
replace nac=nac1 if othcoup==0;
replace educ=educ1 if othcoup==0;
replace health=health1 if othcoup==0;
replace employee=employee1 if othcoup==0;
replace selfemployed=selfemployed1 if othcoup==0;
replace retiree=retiree1 if othcoup==0;
replace disable=disable1 if othcoup==0;
replace student=student1 if othcoup==0;
replace housew=housew1 if othcoup==0;
replace oth_inact=oth_inact1 if othcoup==0;
replace unemployed=unemployed1 if othcoup==0;
replace univ=univ1 if othcoup==0;
replace bankjob=bankjob1 if othcoup==0;

/* Gen dummy to identify status of the couple */;
gen pemployee=0;
gen pselfemployed=0;
gen punemployed=0;
gen pretiree=0;
gen pdisable=0;
gen pstudent=0;
gen phousew=0;
gen poth_inact=0;
gen puniv=0;
gen pnac=0;

forvalues i=2(1)9 {;
	replace punemployed=1 if othcoup`i'==0 & unemployed`i'==1 & relref`i'==2;
	replace pemployee=1 if othcoup`i'==0 & employee`i'==1 & relref`i'==2;
	replace pretiree=1 if othcoup`i'==0 & retiree`i'==1 & relref`i'==2;
	replace pselfemployed=1 if othcoup`i'==0 & selfemployed`i'==1 & relref`i'==2;
	replace pdisable=1 if othcoup`i'==0 & disable`i'==1 & relref`i'==2;
	replace pstudent=1 if othcoup`i'==0 & student`i'==1 & relref`i'==2;
	replace phousew=1 if othcoup`i'==0 & housew`i'==1 & relref`i'==2;
	replace poth_inact=1 if othcoup`i'==0 & oth_inact`i'==1 & relref`i'==2;
	replace puniv=1 if othcoup`i'==0 & univ`i'==1 & relref`i'==2;
	replace pnac=1 if othcoup`i'==0 & nac`i'==1 & relref`i'==2;

	replace punemployed=1 if othcoup`i'==1 & unemployed1==1 & relref`i'==2;
	replace pemployee=1 if othcoup`i'==1 & employee1==1 & relref`i'==2;
	replace pretiree=1 if othcoup`i'==1 & retiree1==1 & relref`i'==2;
	replace pselfemployed=1 if othcoup`i'==1 & selfemployed1==1 & relref`i'==2;
	replace pdisable=1 if othcoup`i'==1 & disable1==1 & relref`i'==2;
	replace pstudent=1 if othcoup`i'==1 & student1==1 & relref`i'==2;
	replace phousew=1 if othcoup`i'==1 & housew1==1 & relref`i'==2;
	replace poth_inact=1 if othcoup`i'==1 & oth_inact1==1 & relref`i'==2;
	replace puniv=1 if othcoup`i'==1 & univ1==1 & relref`i'==2;
	replace pnac=1 if othcoup`i'==1 & nac1==1 & relref`i'==2;
	};
	
* Define other reference person for housew/student households: specifically, take as reference person those sons or daughters that are
*main earners;

egen maxw=rowmax(wage1 wage2 wage3 wage4 wage5 wage6 wage7 wage8 wage9);

forvalues i=2(1)9{;
		gen oth_member`i'=0;
		replace oth_member`i'=1 if (housew==1 | student==1) & wage`i'==maxw & maxw>0;
		replace employee`i'=1 if oth_member`i'==1;
		replace sex=sex`i' if oth_member`i'==1;
		*replace psex=0 if oth_member`i'==1 /* Assume has no couple */;
		replace nac=nac`i' if oth_member`i'==1;
		replace pnac=0 if oth_member`i'==1 /* Assume has no couple */;
		replace educ=educ`i' if oth_member`i'==1;
		*replace peduc=0 if oth_member`i'==1 /* Assume has no couple */;
		replace health=health`i' if oth_member`i'==1;
		*replace phealth=0 if oth_member`i'==1 /* Assume has no couple */;
		replace employee=employee`i' if oth_member`i'==1;
		replace pemployee=0 if oth_member`i'==1 /* Assume has no couple */;
		replace selfemployed=selfemployed`i' if oth_member`i'==1;
		replace pselfemployed=0 if oth_member`i'==1 /* Assume has no couple */;
		replace retiree=retiree`i' if oth_member`i'==1;
		replace pretiree=0 if oth_member`i'==1 /* Assume has no couple */;
		replace disable=disable`i' if oth_member`i'==1;
		replace pdisable=0 if oth_member`i'==1 /* Assume has no couple */;
		replace student=student`i' if oth_member`i'==1;
		replace pstudent=0 if oth_member`i'==1 /* Assume has no couple */;
		replace housew=housew`i' if oth_member`i'==1;
		replace phousew=0 if oth_member`i'==1 /* Assume has no couple */;
		replace oth_inact=oth_inact`i' if oth_member`i'==1;
		replace poth_inact=0 if oth_member`i'==1 /* Assume has no couple */;
		replace unemployed=unemployed`i' if oth_member`i'==1;
		replace punemployed=0 if oth_member`i'==1 /* Assume has no couple */;
		replace univ=univ`i' if oth_member`i'==1;
		replace puniv=0 if oth_member`i'==1 /* Assume has no couple */;
		};	


egen auxoth=rowtotal(oth_member*);
		
/* Choose other household member if there are no employees*/;
forvalues i=2(1)9{;
		gen oth2_member`i'=0;
		replace oth2_member`i'=1 if (housew==1 | student==1) & auxoth==0 & selfemployed`i'==1;
		replace selfemployed`i'=1 if oth2_member`i'==1;
		replace sex=sex`i' if oth2_member`i'==1;
		*replace psex=0 if oth_member`i'==1 /* Assume has no couple */;
		replace nac=nac`i' if oth2_member`i'==1;
		replace pnac=0 if oth2_member`i'==1 /* Assume has no couple */;
		replace educ=educ`i' if oth2_member`i'==1;
		*replace peduc=0 if oth_member`i'==1 /* Assume has no couple */;
		replace health=health`i' if oth2_member`i'==1;
		*replace phealth=0 if oth_member`i'==1 /* Assume has no couple */;
		replace employee=employee`i' if oth2_member`i'==1;
		replace pemployee=0 if oth2_member`i'==1 /* Assume has no couple */;
		replace selfemployed=selfemployed`i' if oth2_member`i'==1;
		replace pselfemployed=0 if oth2_member`i'==1 /* Assume has no couple */;
		replace retiree=retiree`i' if oth2_member`i'==1;
		replace pretiree=0 if oth2_member`i'==1 /* Assume has no couple */;
		replace disable=disable`i' if oth2_member`i'==1;
		replace pdisable=0 if oth2_member`i'==1 /* Assume has no couple */;
		replace student=student`i' if oth2_member`i'==1;
		replace pstudent=0 if oth2_member`i'==1 /* Assume has no couple */;
		replace housew=housew`i' if oth2_member`i'==1;
		replace phousew=0 if oth2_member`i'==1 /* Assume has no couple */;
		replace oth_inact=oth_inact`i' if oth2_member`i'==1;
		replace poth_inact=0 if oth2_member`i'==1 /* Assume has no couple */;
		replace unemployed=unemployed`i' if oth2_member`i'==1;
		replace punemployed=0 if oth2_member`i'==1 /* Assume has no couple */;
		replace univ=univ`i' if oth2_member`i'==1;
		replace puniv=0 if oth2_member`i'==1 /* Assume has no couple */;
		};	

gen bhealth=0;
replace bhealth=1 if health>=4;

egen auxoth2=rowtotal(oth2_member*);
	
egen aux=rowtotal(employee selfemployed unemployed retiree disable student housew oth_inact);
keep if aux==1;	

gen age=2014-nac;
replace age=age/10;

** Age dummies **;
gen age1=0;
replace age1=1 if age>=3 & age<3.5;

gen age2=0;
replace age2=1 if age>=3.5 & age<4;

gen age3=0;
replace age3=1 if age>=4 & age<4.5;

gen age4=0;
replace age4=1 if age>=4.5 & age<5;

gen age5=0;
replace age5=1 if age>=5 & age<5.5;

gen age6=0;
replace age6=1 if age>=5.5 & age<6;

gen age7=0;
replace age7=1 if age>=6 & age<6.5;

gen age8=0;
replace age8=1 if age>=6.5 & age<7;

gen age9=0;
replace age9=1 if age>=7 & age<7.6;

gen age_inst=0;
replace age_inst=1 if age1==1;
replace age_inst=2 if age2==1;
replace age_inst=3 if age3==1;
replace age_inst=4 if age4==1;
replace age_inst=5 if age5==1;
replace age_inst=6 if age6==1;
replace age_inst=7 if age7==1;
replace age_inst=8 if age8==1;
replace age_inst=9 if age9==1;

gen agesq=age^2;

gen page=2014-nac;
replace page=page/10;

** page dummies **;
gen page1=0;
replace page1=1 if page>=3 & page<3.5;

gen page2=0;
replace page2=1 if page>=3.5 & page<4;

gen page3=0;
replace page3=1 if page>=4 & page<4.5;

gen page4=0;
replace page4=1 if page>=4.5 & page<5;

gen page5=0;
replace page5=1 if page>=5 & page<5.5;

gen page6=0;
replace page6=1 if page>=5.5 & page<6;

gen page7=0;
replace page7=1 if page>=6 & page<6.5;

gen page8=0;
replace page8=1 if page>=6.5 & page<7;

gen page9=0;
replace page9=1 if page>=7 & page<7.6;

gen page_inst=0;
replace page_inst=1 if page1==1;
replace page_inst=2 if page2==1;
replace page_inst=3 if page3==1;
replace page_inst=4 if page4==1;
replace page_inst=5 if page5==1;
replace page_inst=6 if page6==1;
replace page_inst=7 if page7==1;
replace page_inst=8 if page8==1;
replace page_inst=9 if page9==1;

gen pagesq=page^2;



/* Drop multiple-unrelated households */;

egen minval=rowmin(relref*);
replace minval=0 if minval==.;

gen madult=0;
replace madult=1 if minval==9 & (year==2002 | year==2005);
replace madult=1 if minval==12 & (year==2008 | year==2011);



********************************************;
rename p2_3 instal /* Year of house purchasing (assume to be the same as instalment) */;
rename p2_4 price_a /* Purchasing price */;
rename p2_5 price_b /* Price of hypothetical sell */;


		  ******************* Application for loans (2)*****************;

rename p3_12a treject;
rename p3_12b preject;

/* Totally reject loan application (any) */;		  
gen reject=0;
replace reject=1 if treject==1;
replace reject=0 if treject==.;

forvalues i=1(1)4 {;
	rename p3_13s`i' rnoappl`i' /* Reasons of not applying for a loan */;
	rename p3_15s`i' rreject`i' /* Reasons of rejecting */;
	};

	
gen applic2=0;
replace applic2=1 if rnoappl1==.;

/* Discouraged borrowers: refuse to apply for a loan because it would be turned down (any member of the household. Exclude debt holders */;
gen discour=0;
replace discour=1 if (rnoappl1==4 | rnoappl2==4 | rnoappl3==4 | rnoappl4==4) & anydebt==0 & applic2==0;

/* Applicant: whether the household made any loan application or refused beacuse of sure rejecting */;
gen applic=0;
replace applic=1 if applic2>0 | discour==1 | anydebt==1;

/* Partially rejected loan application (any) */;
gen partrej=0;
replace partrej=1 if preject==1;
replace partrej=0 if preject==.;
		
gen totpartrej=0;
replace totpartrej=1 if (reject==1 | partrej==1);
replace totpartrej=1 if discour==1;
**replace totpartrej=0 if anydebt==1;

/* Rationed: discouraged or reject totally or partially */;
gen ration2=0;
replace ration2=1 if discour==1 | partrej==1 | reject==1;
replace ration2=0 if ration2==.;
*replace ration2=0 if anydebt==1;

/* Rationed: discouraged or totally rejected */;
gen ration=0;
replace ration=1 if discour==1 | reject==1;
replace ration=0 if ration==.;
*replace ration=0 if anydebt==1;

*replace anydebt=1 if applic==1 & anydebt==0 & ration==0 /* Applied, borrowed and repaid, and report zero borrowing */;

						   
**************** INCOME *********************;
*rename renthog hhincome /* annual 2001 for 2002 wave, 2004 (2005 wave), 2007 (2008 wave) */;
replace hhincome=hhincome/acpi*100;
gen lincome=log(1+hhincome);
replace hhincome=hhincome/10000;
gen hhincomesq=(hhincome^2)/10000;

rename mrenthog mhhincome /* month oct2002 - may2003 (2002), nov2005 - may2006 (2005), nov2008 - jun2009 (2008) */;
replace mhhincome=mhhincome/mcpi*100;
gen mhhincomesq=mhhincome^2;


************** FINANCIAL HELP FROM RELATIVES AND FRIENDS *******************;
/*monetary assistance from friends or family members outside the
household, or from a partner no longer living in the household*/;

rename p6_59 finhelp;
replace finhelp=0 if finhelp==2;

rename p6_60 amounthelp;
replace amounthelp=amounthelp/mcpi*100;

************ ARREARS *****************;

/* In the last twelve months have you had any financial
difficulties which resulted in your delaying the payment of any of
your debts? */;

gen arrears=0;
replace arrears=1 if p9_16==1;

*replace anydebt=1 if arrears==1;
replace applic=1 if anydebt==1;
*replace ration=0 if arrears==1;
replace discour=0 if anydebt==1;

gen applic_non_disc=0;
replace applic_non_disc=1 if applic==1 & discour==0;

gen repay=.;
replace repay=1 if arrears==0 & anydebt==1;
replace repay=0 if arrears==1;

* Risk Aversion;
rename p9_11 riskaver;

gen risklot=.;
replace risklot=0 if riskaver==2 | riskaver==3 | riskaver==4;
replace risklot=1 if riskaver==1;

gen riskfair=.;
replace riskfair=0 if riskaver==1 | riskaver==3 | riskaver==4;
replace riskfair=1 if riskaver==2;

gen risksome=.;
replace risksome=0 if riskaver==1 | riskaver==2 | riskaver==4;
replace risksome=1 if riskaver==3;

gen norisk=.;
replace norisk=0 if riskaver==1 | riskaver==2 | riskaver==3;
replace norisk=1 if riskaver==4;

******** Dummies for hhincome ********;
_pctile hhincome, p(20,40,60,80);
scalar r1=r(r1);
scalar r2=r(r2);
scalar r3=r(r3);
scalar r4=r(r4);

gen hhincome1=0;
replace hhincome1=1 if hhincome<scalar(r1);

gen hhincome2=0;
replace hhincome2=1 if hhincome>=scalar(r1) & hhincome<scalar(r2);

gen hhincome3=0;
replace hhincome3=1 if hhincome>=scalar(r2) & hhincome<scalar(r3);

gen hhincome4=0;
replace hhincome4=1 if hhincome>=scalar(r3)  & hhincome<scalar(r4);

gen hhincome5=0;
replace hhincome5=1 if hhincome>scalar(r4);

gen inc_inst=0;
replace inc_inst=1 if hhincome1==1;
replace inc_inst=2 if hhincome2==1;
replace inc_inst=3 if hhincome3==1;
replace inc_inst=4 if hhincome4==1;


*********** Dummies for income II ************;
replace hhincome=hhincome*10000;

gen hh1=0;
replace hh1=1 if hhincome<=15000;
gen hh2=0;
replace hh2=1 if hhincome>15000 & hhincome<=25000;
gen hh3=0;
replace hh3=1 if hhincome>25000 & hhincome<=35000;
gen hh4=0;
replace hh4=1 if hhincome>35000 & hhincome<=45000;
gen hh5=0;
replace hh5=1 if hhincome>45000 & hhincome<=57000;
gen hh6=0;
replace hh6=1 if hhincome>57000;
*/;
gen hh_inst=0;
replace hh_inst=1 if hh1==1;
replace hh_inst=2 if hh2==1;
replace hh_inst=3 if hh3==1;
replace hh_inst=4 if hh4==1;
replace hh_inst=5 if hh5==1;
replace hh_inst=6 if hh6==1;
*replace hh_inst=7 if hh7==1;
*replace hh_inst=8 if hh8==1;
*replace hh_inst=9 if hh9==1;

replace hhincome=hhincome/10000;


*********** Dummies for nwealth ************;

replace nwealth=nwealth/acpi*100;
gen lnwealth=.;
replace lnwealth=log(1+abs(nwealth)) if nwealth>=0;
replace lnwealth=-log(1+abs(nwealth)) if nwealth<0;

gen nw1=0;
replace nw1=1 if nwealth<=10000;
gen nw2=0;
replace nw2=1 if nwealth>10000 & nwealth<=80000;
gen nw3=0;
replace nw3=1 if nwealth>80000 & nwealth<=200000;
gen nw4=0;
replace nw4=1 if nwealth>200000 & nwealth<=500000;
gen nw5=0;
replace nw5=1 if nwealth>500000;


***** Generate alternative wealth variables *****;
gen housewealth= nwealth;
replace housewealth=housewealth-vmresid/acpi*100+vdebtmresid/acpi*100 if debtmresid==1;

replace housewealth=housewealth + vdebtprop1/acpi*100 - p2_39_1*(p2_37_1/100)/acpi*100 if vdebtprop1>0;
replace housewealth=housewealth + vdebtprop2/acpi*100 - p2_39_2*(p2_37_1/100)/acpi*100 if vdebtprop2>0;
replace housewealth=housewealth + vdebtprop3/acpi*100 - p2_39_3*(p2_37_1/100)/acpi*100 if vdebtprop3>0;
replace housewealth=housewealth + vdebtprop4/acpi*100 - p2_39_4*(p2_37_1/100)/acpi*100 if vdebtprop4>0;

gen lhousingw=.;
replace lhousingw=log(1+abs(housewealth)) if housewealth>=0;
replace lhousingw=-log(1+abs(housewealth)) if housewealth<0;

gen buswealth=nwealth;
replace buswealth=buswealth-valhog/acpi*100+vbusloan;

gen lbusloanw=.;
replace lbusloanw=log(1+abs(buswealth)) if buswealth>=0;
replace lbusloanw=-log(1+abs(buswealth)) if buswealth<0;

gen cardwealth=nwealth;
replace cardwealth=cardwealth+vcredcard;

gen lcredcardw=.;
replace lcredcardw=log(1+abs(cardwealth)) if cardwealth>=0;
replace lcredcardw=-log(1+abs(cardwealth)) if cardwealth<0;

gen otherwealth=nwealth;
replace otherwealth=otherwealth-vrestbis;

gen lrestbisw=.;
replace lrestbisw=log(1+abs(otherwealth)) if otherwealth>=0;
replace lrestbisw=-log(1+abs(otherwealth)) if otherwealth<0;

*********** Dummies for housing wealth ************;

gen housingw1=0;
replace housingw1=1 if housewealth<=10000;
gen housingw2=0;
replace housingw2=1 if housewealth>10000 & housewealth<=80000;
gen housingw3=0;
replace housingw3=1 if housewealth>80000 & housewealth<=200000;
gen housingw4=0;
replace housingw4=1 if housewealth>200000 & housewealth<=500000;
gen housingw5=0;
replace housingw5=1 if housewealth>500000;

*********** Dummies for business wealth ************;

gen busloanw1=0;
replace busloanw1=1 if buswealth<=10000;
gen busloanw2=0;
replace busloanw2=1 if buswealth>10000 & buswealth<=80000;
gen busloanw3=0;
replace busloanw3=1 if buswealth>80000 & buswealth<=200000;
gen busloanw4=0;
replace busloanw4=1 if buswealth>200000 & buswealth<=500000;
gen busloanw5=0;
replace busloanw5=1 if buswealth>500000;

*********** Dummies for credit card wealth ************;

gen credcardw1=0;
replace credcardw1=1 if cardwealth<=10000;
gen credcardw2=0;
replace credcardw2=1 if cardwealth>10000 & cardwealth<=80000;
gen credcardw3=0;
replace credcardw3=1 if cardwealth>80000 & cardwealth<=200000;
gen credcardw4=0;
replace credcardw4=1 if cardwealth>200000 & cardwealth<=500000;
gen credcardw5=0;
replace credcardw5=1 if cardwealth>500000;


*********** Dummies for other debts wealth ************;

gen restbisw1=0;
replace restbisw1=1 if otherwealth<=10000;
gen restbisw2=0;
replace restbisw2=1 if otherwealth>10000 & otherwealth<=80000;
gen restbisw3=0;
replace restbisw3=1 if otherwealth>80000 & otherwealth<=200000;
gen restbisw4=0;
replace restbisw4=1 if otherwealth>200000 & otherwealth<=500000;
gen restbisw5=0;
replace restbisw5=1 if otherwealth>500000;


foreach f of var * { ;
	rename `f' `f'_imp`x' ;
} ;
rename h_2014_imp`x' h2014;
drop p6*;
save wave2014_imp`x'.dta, replace;

};

cd "H:\Mi unidad\Grant_new\EFF";
use "H:\Mi unidad\Grant_new\EFF\Imputation1\wave2014_imp1.dta";
joinby h2014 using "H:\Mi unidad\Grant_new\EFF\Imputation2\wave2014_imp2";
joinby h2014 using "H:\Mi unidad\Grant_new\EFF\Imputation3\wave2014_imp3";
joinby h2014 using "H:\Mi unidad\Grant_new\EFF\Imputation4\wave2014_imp4";
joinby h2014 using "H:\Mi unidad\Grant_new\EFF\Imputation5\wave2014_imp5";



save "H:\Mi unidad\Grant_new\wave2014.dta", replace;

erase "H:\Mi unidad\Grant_new\EFF\Imputation1\wave2014_imp1.dta";
erase "H:\Mi unidad\Grant_new\EFF\Imputation2\wave2014_imp2.dta";
erase "H:\Mi unidad\Grant_new\EFF\Imputation3\wave2014_imp3.dta";
erase "H:\Mi unidad\Grant_new\EFF\Imputation4\wave2014_imp4.dta";
erase "H:\Mi unidad\Grant_new\EFF\Imputation5\wave2014_imp5.dta";


*************************************************************************;
************************************* 2017 ******************************;
*************************************************************************;

foreach x in 1 2 3 4 5{; 


cd "H:\Mi unidad\Grant_new\EFF\Imputation`x'";

use seccion6_2017_imp`x'.dta, clear;

joinby h_2017 using otras_secciones_2017_imp`x'.dta;

gen year=2017;

********************************************************************;
** Annual and monthly consumer price index to be used (base 2010) **;
********************************************************************;

gen acpi=81.06;
replace acpi=88.96 if year==2005;
replace acpi=98.52 if year==2008;
replace acpi=103.20 if year==2011;
replace acpi=107.05 if year==2014;
replace acpi=108.38 if year==2017;

gen mcpi=82.73 					 /* mean oct02-may03 */;
replace mcpi=91.14 if year==2005 /* mean nov05-may06 */;
replace mcpi=98.10 if year==2008 /* mean nov08-jun09 */;
replace mcpi=104.33 if year==2011 /* mean oct11-apr12 */;
replace mcpi=106.42 if year==2014 /* mean sept14-mar15*/;
replace mcpi=109.51 if year==2017 /* mean oct17-jun18*/;

********************************************************************;
********************************************************************;

*NET WEALTH AND INCOME;

*1.- FOR THE PERCENTAGE OF HOUSEHOLDS OWNING THAT ASSET;

*REAL ASSETS;

*MAIN RESIDENCE;
*To calculate the percentage of households that own their main residence we use the variable p2_1;

gen np2_1=(p2_1==2 & p2_5>0 & p2_5~=.);

gen owner=0;
replace owner=1 if np2_1==1;

gen renter=0 /*renter or (only 2014) renter with purchase option*/;
replace renter=1 if p2_1==1;

gen freeuse=0;
replace freeuse=1 if p2_1==3;

*OTHER REAL ESTATE PROPERTIES;
*To calculate the percentage of households that own other real estate properties we use the variable np2_32; 
gen np2_32=((p2_32==1 & p2_33>=1 & p2_33~=. & p2_39_1>0 & p2_39_1~=.)|
            (p2_32==1 & p2_33>=2 & p2_33~=. & p2_39_2>0 & p2_39_2~=.)|
            (p2_32==1 & p2_33>=3 & p2_33~=. & p2_39_3>0 & p2_39_3~=.)|
            (p2_32==1 & p2_33>3  & p2_33~=. & p2_39_4>0 & p2_39_4~=.));

gen othowner=.;
replace othowner=1 if np2_32==1;
replace othowner=0 if np2_32==0;

*JEWELLERY, WORKS OF ART, ANTIQUES;
*To calculate the percentage of households that own jewellery, works of art and antiques we use the variable np2_82;
gen np2_82=(p2_82==1 & p2_84>0 & p2_84~=.);

gen jewel=.;
replace jewel=0 if np2_82==0;
replace jewel=1 if np2_82==1;


*VALOR DEL NEGOCIO POR TRABAJOS POR CUENTA PROPIA;
*VALUE OF BUSINESSES RELATED TO SELF-EMPLOYMENT;
gen haveneg =(p4_101==1);

gen valhog =0;
replace valhog =valhog + p4_111_1 if p4_101==1 & p4_111_1>0 & p4_111_1~=.;
replace valhog =valhog + p4_111_2 if p4_101==1 & p4_111_2>0 & p4_111_2~=.;
replace valhog =valhog + p4_111_3 if p4_101==1 & p4_111_3>0 & p4_111_3~=.;
replace valhog =valhog + p4_111_4 if p4_101==1 & p4_111_4>0 & p4_111_4~=.;
replace valhog =valhog + p4_111_5 if p4_101==1 & p4_111_5>0 & p4_111_5~=.;
replace valhog =valhog + p4_111_6 if p4_101==1 & p4_111_6>0 & p4_111_6~=.;

gen havenegval =(haveneg==1 & valhog>0);


*ALGUN TIPO DE ACTIVO REAL;
*SOME KIND OF REAL ASSET;

gen  tienereal=(np2_1==1|np2_32==1|np2_82==1| havenegval==1);


*ACTIVOS FINANCIEROS;
*FINANCIAL ASSETS;


*ACCOUNTS AND DEPOSITS USABLE FOR PAYMENTS;
*To calculate the percentage of households that own accounts and deposits usable for payments and that declare a strictly positive value 
*for the balance of those accounts we generate a new variable;

gen np4_5=(p4_5==1 & p4_7_3>0 & p4_7_3~=.);
rename np4_5 account_pay;
label var account_pay "households that own accounts and deposits usable for payments and that declare a strictly positive value";

*LISTED SHARES;
*To calculate the percentage of households that own listed and that declare a strictly positive value for that portfolio we generate a new variable;

gen np4_10=(p4_10==1 & p4_15>0 & p4_15~=.);

rename np4_10 listshare;
label var listshare "household that own listed shares";


*UNLISTED SHARES AND OTHER EQUITY;
*To calculate the percentage of households that own unlisted shares and other equity and that declare a strictly positive
* value for that portfolio we generate a new variable;

gen np4_18=(p4_18==1 & p4_24>0 & p4_24~=.);
rename np4_18 unlistshare;
label var unlistshare "household that own unlisted shares and other equity";


*FIXED-INCOME SECURITIES;
*To calculate the percentage of households that own fixed-income securities and that declare a strictly positive value for that portfolio we generate a new variable;

gen np4_33=(p4_33==1 & p4_35>0 & p4_35~=.);

rename np4_33 fixsec;
label var fixsec "household that own fixed-income securities ";

*MUTUAL FUNDS (FFII);
*To calculate the percentage of households that own mutual funds and that declare a strictly positive value for that portfolio we generate a new variable;

gen np4_27=((p4_27==1 & p4_28>=1 & p4_28~=. & p4_31_1>0 & p4_31_1~=.)|
            (p4_27==1 & p4_28>=2 & p4_28~=. & p4_31_2>0 & p4_31_2~=.)|
            (p4_27==1 & p4_28>=3 & p4_28~=. & p4_31_3>0 & p4_31_3~=.)|
            (p4_27==1 & p4_28>=4 & p4_28~=. & p4_31_4>0 & p4_31_4~=.)|
            (p4_27==1 & p4_28>=5 & p4_28~=. & p4_31_5>0 & p4_31_5~=.)|
            (p4_27==1 & p4_28>=6 & p4_28~=. & p4_31_6>0 & p4_31_6~=.)|
            (p4_27==1 & p4_28>=7 & p4_28~=. & p4_31_7>0 & p4_31_7~=.)|
            (p4_27==1 & p4_28>=8 & p4_28~=. & p4_31_8>0 & p4_31_8~=.)|
            (p4_27==1 & p4_28>=9 & p4_28~=. & p4_31_9>0 & p4_31_9~=.)|
            (p4_27==1 & p4_28>9 & p4_28~=. & p4_31_10>0 & p4_31_10~=.));

rename np4_27 mutfunds;
label var mutfunds "household that own mutual funds";

*CUENTAS VIVIENDA Y CUENTAS NO UTILIZABLES PARA REALIZAR PAGOS;
*Para calcular la proporción de hogares que poseen cuentas y depósitos no utilizables para realizar pagos generamos una nueva variable cuentas;

*HOUSE-PURCHASE SAVINGS ACCOUNTS AND ACCOUNTS NOT USABLE FOR PAYMENTS;
*To calculate the percentage of households that own house-purchase saving accounts and/or accounts not usable for payments and 
*that declare a strictly positive value for the balance of those accounts we generate a new variable;

gen cuentas=((p4_3==1 & p4_7_1>0 & p4_7_1~=.)|(p4_4==1 & p4_7_2>0 & p4_7_2~=.));

rename cuentas account_nopay;
label var account_nopay "household that own accounts and deposits not usable for payments";


*PENSION SCHEMES (plan pensiones);
*To calculate the percentage of households that own pension schemes and that declare a strictly positive value for the balance of those pension schemes we generate a new variable;

gen np5_1=((p5_1==1 & p5_1a>=1 & p5_1a~=. & p5_7_1>0 & p5_7_1~=.)|
           (p5_1==1 & p5_1a>=2 & p5_1a~=. & p5_7_2>0 & p5_7_2~=.)|
           (p5_1==1 & p5_1a>=3 & p5_1a~=. & p5_7_3>0 & p5_7_3~=.)|
           (p5_1==1 & p5_1a>=4 & p5_1a~=. & p5_7_4>0 & p5_7_4~=.)|
           (p5_1==1 & p5_1a>=5 & p5_1a~=. & p5_7_5>0 & p5_7_5~=.)|
           (p5_1==1 & p5_1a>=6 & p5_1a~=. & p5_7_6>0 & p5_7_6~=.)|
           (p5_1==1 & p5_1a>=7 & p5_1a~=. & p5_7_7>0 & p5_7_7~=.)|
           (p5_1==1 & p5_1a>=8 & p5_1a~=. & p5_7_8>0 & p5_7_8~=.)|
           (p5_1==1 & p5_1a>=9 & p5_1a~=. & p5_7_9>0 & p5_7_9~=.)|
           (p5_1==1 & p5_1a>9 & p5_1a~=. & p5_7_10>0 & p5_7_10~=.));

rename np5_1 penplan;
label var penplan "household that own pension schemes";
*SEGUROS DE VIDA;
*Para calcular la proporción de hogares que tienen seguros tipo unit linked o mixto generamos una nueva variable;

*To calculate the percentage of households that own unit-linked or mixed life insurance we generate a new variable;

gen seguro=((p5_9a==1 & p5_10a>=1 & p5_10a~=. & p5_13_1==2 & p5_14_1>0 & p5_14_1~=.)|
                    (p5_9a==1 & p5_10a>=2 & p5_10a~=. & p5_13_2==2 & p5_14_2>0 & p5_14_2~=.)|
                    (p5_9a==1 & p5_10a>=3 & p5_10a~=. & p5_13_3==2 & p5_14_3>0 & p5_14_3~=.)|
                    (p5_9a==1 & p5_10a>=4 & p5_10a~=. & p5_13_4==2 & p5_14_4>0 & p5_14_4~=.)|
                    (p5_9a==1 & p5_10a>=5 & p5_10a~=. & p5_13_5==2 & p5_14_5>0 & p5_14_5~=.)|
                    (p5_9a==1 & p5_10a>5 &   p5_10a~=. & p5_13_6==2 & p5_14_6>0 & p5_14_6~=.)|
	       (p5_9a==1 & p5_10a>=1 & p5_10a~=. & p5_13_1==3 & p5_14_1>0 & p5_14_1~=.)|
                    (p5_9a==1 & p5_10a>=2 & p5_10a~=. & p5_13_2==3 & p5_14_2>0 & p5_14_2~=.)|
                    (p5_9a==1 & p5_10a>=3 & p5_10a~=. & p5_13_3==3 & p5_14_3>0 & p5_14_3~=.)|
                    (p5_9a==1 & p5_10a>=4 & p5_10a~=. & p5_13_4==3 & p5_14_4>0 & p5_14_4~=.)|
                    (p5_9a==1 & p5_10a>=5 & p5_10a~=. & p5_13_5==3 & p5_14_5>0 & p5_14_5~=.)|
                    (p5_9a==1 & p5_10a>5 &   p5_10a~=. & p5_13_6==3 & p5_14_6>0 & p5_14_6~=.));	

rename seguro lifeinsur;
label var lifeinsur "household that own unit-linked or mixed life insurance";

*PLANES DE PENSIONES INCLUYENDO SEGUROS DE VIDA DE INVERSION O MIXTOS;
*PENSION SCHEMES INCLUDING UNIT-LINKED OR MIXED LIFE INSURANCE;

gen penseg=(penplan==1|lifeinsur==1);

*PORTFOLIOS UNDER MANAGEMENT (carteras gestionadas);

gen cart_gest=((p4_41==1 & p4_42==1) & p4_43>0 & p4_43~=.);


*OTHER FINANCIAL ASSETS; 

*To calculate the percentage of households to whom the business or other people owe money we generate the variable sideuda; 


*PROGRAMA PARA CALCULAR LO QUE LES DEBEN LOS NEGOCIOS A LOS DISTINTOS MIEMBROS DEL HOGAR (P4_116);
*PROGRAM TO OBTAIN WHAT THE BUSINESSES OWE TO THE DIFFERENT HOUSEHOLD MEMBERS (P4_116);

gen valdeuhog=0;
gen havedeuhog=0;
forvalues m=1/6   {;
	replace valdeuhog=valdeuhog+p4_116_`m' if (p4_116_`m'>0 & p4_116_`m'~=.);
	replace havedeuhog=1 if (p4_115_`m'==1);
	};
gen sideuda=((havedeuhog ==1 & valdeuhog>0)|(p4_37==1 & p4_38>0 & p4_38~=.));

rename sideuda creditor;
label var creditor "household to whom the business or other people owe money";

*ALGUN TIPO DE ACTIVO FINANCIERO;
*SOME TYPE OF FINANCIAL ASSET;

gen tienefin=(account_pay==1|listshare==1|unlistshare==1|fixsec==1|mutfunds==1|account_nopay==1|penplan==1|lifeinsur==1|creditor==1|cart_gest==1);

*ALGUN TIPO DE ACTIVO;
*SOME TYPE OF ASSET;

gen tiene=(tienereal==1|tienefin==1);
rename tiene anyasset;




*2.- PARA EL VALOR DE DICHOS ACTIVOS;
*2.- FOR THE VALUE OF THOSE ASSETS;

*ACTIVOS REALES;
*REAL ASSETS;

*MAIN RESIDENCE;
*To obtain the value of the main residence we use the variable p2_5;
gen np2_5=p2_5 if p2_1b==1;
replace np2_5=p2_5*(p2_1c/100) if p2_1b==2;

rename np2_5 vmresid;
label var vmresid "value of the main residence";

*OTHER REAL ESTATE PROPERTIES;
*To obtain the value of the other real estate properties we generate a new variable;

gen otraspr=0;
replace otraspr=otraspr+p2_39_1*(p2_37_1/100) if (p2_33>=1 & p2_33~=. & p2_39_1>=0 & p2_39_1~=. & p2_37_1>0 & p2_37_1~=.);
replace otraspr=otraspr+p2_39_2 *(p2_37_2/100) if (p2_33>=2 & p2_33~=. & p2_39_2>=0 & p2_39_2~=. & p2_37_2>0 & p2_37_2~=.);
replace otraspr=otraspr+p2_39_3* (p2_37_3/100) if (p2_33>=3 & p2_33~=. & p2_39_3>=0 & p2_39_3~=. & p2_37_3>0 & p2_37_3~=.);
replace otraspr=otraspr+p2_39_4 if (p2_33>3 & p2_33~=. & p2_39_4>=0 & p2_39_4~=.);

rename otraspr vothprop;
label var vothprop "value of the other real estate properties";


*JEWELLERY, WORKS OF ART, ANTIQUES;
*To obtain the value of the jewellery, works of art and antiques we use the variable p2_84;
rename p2_84 vjewel;
label var vjewel "value of the jewellery, works of art and antiques";

*VALOR DEL NEGOCIO POR TRABAJOS POR CUENTA PROPIA;
*la mediana del valor del negocio será la mediana de valhog if havenegval==1; 

*TBD;

*VALUE OF THE BUSINESS RELATED TO SELF-EMPLOYMENT;
*The median of the business value is equal to the median of valhog if havenegval==1;


*ACTIVOS FINANCIEROS;
*FINANCIAL ASSETS;

*CUENTAS Y DEPOSITOS UTILIZABLES PARA REALIZAR PAGOS;
*Para calcular el saldo de las cuentas y depósitos para realizar pagos utilizamos la variable p4_7_3;


*ACCOUNTS AND DEPOSITS USABLE FOR PAYMENTS;
*To obtain the balance of the accounts and deposits usable for payments we use the variable p4_7_3;
rename p4_7_3 vaccount_pay;



*ACCIONES COTIZADAS EN BOLSA;
*Para calcular el valor de las acciones cotizadas utilizamos la variable p4_15;


*LISTED SHARES;
*To obtain the value of the listed shares we use the variable p4_15;
rename p4_15 vlistshare;

*ACCIONES NO COTIZADAS EN BOLSA Y PARTICIPACIONES;
*Para calcular el valor de las acciones no cotizadas y participaciones utilizamos la variable p4_24;

*UNLISTED SHARES ANDOTHER EQUITY;
*To obtain the value of the unlisted shares and other equity we use the variable p4_24;
rename p4_24 vunlist;

*VALORES DE RENTA FIJA;
*Para calcular el valor de los valores de renta fija utilizamos la variable p4_35;

*FIXED-INCOME SECURITIES;
*To obtain the value of the fixed-income securities we use the variable p4_35;

rename p4_35 vfixsec;

*FONDOS DE INVERSION;
*Para calcular el valor total de los fondos de inversión utilizamos la variable allf calculada como (i) la suma de los valores de cada uno de los fondos 
*de inversión que posee el hogar (p4_31_i, i=1,…,10) si el número de estos fondos es menor o igual a 10, y (ii) el valor total de los fondos de inversión 
*del hogar si posee más de 10 fondos (p4_28a);

*MUTUAL FUNDS;
*To obtain the total value of mutual funds we use the variable allf calculated as (i) the addition of the values of each mutual fund that the household
* owns (p4_31_i, i=1,…,10) if the number of these funds is 10 or less, and (ii) the household mutual funds’ total value if this one owns more than 10 (p4_28a);

egen allf=rowtotal(p4_31*);
replace allf=p4_28a if p4_28>10;
label var allf "Total value of mutual funds";


*CUENTAS VIVIENDA Y CUENTAS NO UTILIZABLES PARA REALIZAR PAGOS;
*Para calcular el saldo de las cuentas y depósitos no utilizables para realizar pagos generamos una nueva variable;

*HOME-PURCHASE SAVINGS ACCOUNTS AND ACCOUNTS NOT USABLE FOR PAYMENTS;
*To obtain the balance of the accounts and deposits not usable for payments we generate a new variable;  

gen salcuentas=0;
replace salcuentas = salcuentas +p4_7_1 if p4_3==1;
replace salcuentas = salcuentas + p4_7_2 if p4_4==1;

rename salcuentas vaccount_nopay;
label var vaccount_nopay "balance of the accounts and deposits not usable for payments";

*PLANES DE PENSIONES;
*Para calcular valor actualizado de los planes de pensiones generamos una nueva variable;

*PENSION SCHEMES;
*To obtain the current value of the pension schemes we generate a new variable;

gen valor=0; 
replace valor = valor +p5_7_1 if (p5_1==1 & p5_7_1>=0 & p5_7_1~=. );
replace valor = valor + p5_7_2 if (p5_1==1 & p5_7_2>=0 & p5_7_2~=.);
replace valor = valor + p5_7_3 if (p5_1==1 & p5_7_3>=0 & p5_7_3~=.);
replace valor = valor + p5_7_4 if (p5_1==1 & p5_7_4>=0 & p5_7_4~=.);
replace valor = valor + p5_7_5 if (p5_1==1 & p5_7_5>=0 & p5_7_5~=.);
replace valor = valor + p5_7_6 if (p5_1==1 & p5_7_6>=0 & p5_7_6~=.);
replace valor = valor + p5_7_7 if (p5_1==1 & p5_7_7>=0 & p5_7_7~=.);
replace valor = valor + p5_7_8 if (p5_1==1 & p5_7_8>=0 & p5_7_8~=.);
replace valor = valor + p5_7_9 if (p5_1==1 & p5_7_9>=0 & p5_7_9~=.);
replace valor = valor + p5_7_10 if (p5_1==1 & p5_7_10>=0 & p5_7_10~=.);


rename valor vpenplan;
label var vpenplan "current value of the pension schemes";

*No consideramos las mutualidades;
*We do not consider mutual insurance;

*SEGUROS DE VIDA;
*Para calcular el valor de estos seguros tipo unit linked o mixto generamos una nueva variable;

*LIFE INSURANCE;
*To obtain the value of the unit-linked or mixed life insurance we generate a new variable;


gen valseg=0;
replace valseg = valseg +p5_14_1 if ((p5_13_1==2| p5_13_1==3) & p5_14_1>=0 & p5_14_1~=.);
replace valseg = valseg +p5_14_2 if ((p5_13_2==2| p5_13_2==3) & p5_14_2>=0 & p5_14_2~=.);
replace valseg = valseg +p5_14_3 if ((p5_13_3==2| p5_13_3==3) & p5_14_3>=0 & p5_14_3~=.);
replace valseg = valseg +p5_14_4 if ((p5_13_4==2| p5_13_4==3) & p5_14_4>=0 & p5_14_4~=.);
replace valseg = valseg +p5_14_5 if ((p5_13_5==2| p5_13_5==3) & p5_14_5>=0 & p5_14_5~=.);
replace valseg = valseg +p5_14_6 if ((p5_13_6==2| p5_13_6==3) & p5_14_6>=0 & p5_14_6~=.);


rename valseg vlifeinsur;
label var vlifeinsur "value of the unit-linked or mixed life insurance";

*PLANES DE PENSIONES INCLUYENDO SEGUROS DE VIDA DE INVERSION O MIXTOS;
*PENSION SCHEMES INCLUDING UNIT-LINKED OR MIXED LIFE INSURANCE;

gen valpenseg=vpenplan+vlifeinsur;
rename valpenseg vpeninsur;
label var vpeninsur "value of pension schemes plus unit-linked or mixed life insurance";

*OTROS ACTIVOS FINANCIEROS;
*Para calcular el valor de la mediana de lo que se debe al hogar, utilizamos las variables valdeuhog y p4_38 y generamos una nueva variable;

*OTHER FINANCIAL ASSETS;
*To obtain the median of how much is owed to the household, we use the variables valdeuhog and p4_38 and generate a new variable; 

gen odeuhog=0;

replace odeuhog = odeuhog +valdeuhog if (valdeuhog>0);
replace odeuhog = odeuhog +p4_38 if (p4_38>0 & p4_38~=.);

rename odeuhog vcreditor;
label var vcreditor "how much is owed to the household";

*CUADRO 7: PROPORCION DE HOGARES Y MEDIANA DEL VALOR DE LOS DISTINTOS TIPOS DE DEUDA PENDIENTES;
*TABLE 7: PERCENTAGE OF HOUSEHOLDS AND VALUE’S MEDIAN OF THE DIFFERENT TYPES OF OUTSTANDING DEBT;

*DEUDAS  CLASIFICADAS POR TIPO DE ACTIVO INMOBILIARIO (TODO TIPO DE PRESTAMOS);
*DEBT CLASSIFIED BY TYPE OF REAL ESTATE ASSET (ALL KIND OF LOANS);

*VIVIENDA PRINCIPAL;
*MAIN RESIDENCE;

*Para calcular la proporción de hogares que tienen deudas pendientes de préstamos solicitados para la adquisición de la vivienda principal, utilizamos p2_8;
*To obtain the percentage of households that have outstanding debt from loans used to purchase their main residence, we generate a new variable;

gen np2_8=p2_8;
replace np2_8=0 if p2_8==.;

rename np2_8 debtmresid;
label var debtmresid "have outstanding debt from loans used to purchase main residence";

*Para calcular el valor de las deudas pendientes de préstamos solicitados para la adquisición de la vivienda principal, generamos una nueva variable;
*To obtain the value of the outstanding debts from loans used to purchase their main residence, we generate a new variable;

gen dvivpral=0;

replace dvivpral= dvivpral +p2_12_1 if  (p2_8a>=1 & p2_8a~=. & p2_12_1>0 & p2_12_1~=.);

replace dvivpral= dvivpral + p2_12_2 if (p2_8a>=2 & p2_8a~=. &  p2_12_2>0 & p2_12_2~=.);

replace dvivpral= dvivpral +p2_12_3  if (p2_8a>=3 & p2_8a~=. & p2_12_3>0 & p2_12_3~=.);

replace dvivpral= dvivpral +p2_12_4  if (p2_8a>3 & p2_8a~=. & p2_12_4>0 & p2_12_4~=.);

rename dvivpral vdebtmresid;
label var vdebtmresid "value of outstanding debts from loans used to purchase main residence";

*OTRAS PROPIEDADES INMOBILIARIAS DIFERENTES DE LA VIVIENDA PRINCIPAL;
*OTHER REAL ESTATE PROPERTIES DIFFERENT FROM THE MAIN RESIDENCE;

*Para calcular la proporción de hogares que tienen deudas pendientes de préstamos solicitados para la adquisición de otras propiedades inmobiliarias diferentes de la vivienda principal, generamos una nueva variable;

*To obtain the percentage of households that have outstanding debts from loans used to purchase other real estate properties different from the main 
*residence, we generate a new variable;

gen dpdte=(p2_50_1==1|p2_50_2==1|p2_50_3==1|p2_50_4==1);
rename dpdte debtothprop;
label var debtothprop "have outstanding debts from loans used to purchase other real estate properties";

*Para calcular el valor de las deudas pendientes de préstamos solicitados para la adquisición de otras propiedades inmobiliarias diferentes de la vivienda principal, generamos cuatro nuevas variables;

*To obtain the value of the outstanding debts from loans used to purchase other real estate properties different from the main residence, we generate
* four new variables;

*PARA LA PRIMERA PROPIEDAD INMOBILIARIA;
*FOR THE FIRST REAL ESTATE PROPERTY;

gen dprop1=0;

replace dprop1= dprop1+p2_55_1_1 if (p2_51_1>=1 & p2_51_1~=.  &  p2_55_1_1>0 & p2_55_1_1~=.);

replace dprop1= dprop1+ p2_55_1_2 if (p2_51_1>=2 & p2_51_1~=.  & p2_55_1_2>0 & p2_55_1_2~=.);

replace dprop1= dprop1+p2_55_1_3  if (p2_51_1>=3 & p2_51_1~=.  & p2_55_1_3>0 & p2_55_1_3~=.);


*PARA LA SEGUNDA PROPIEDAD INMOBILIARIA;
*FOR THE SECOND REAL ESTATE PROPERTY;

gen dprop2=0;

replace dprop2= dprop2+p2_55_2_1 if (p2_51_2>=1 & p2_51_2~=. & p2_55_2_1>0 & p2_55_2_1~=.);

replace dprop2= dprop2+ p2_55_2_2 if (p2_51_2>=2 & p2_51_2~=. & p2_55_2_2>0 & p2_55_2_2~=.);

replace dprop2= dprop2+ p2_55_2_3  if (p2_51_2>=3 & p2_51_2~=. & p2_55_2_3>0 & p2_55_2_3~=.);


*PARA LA TERCERA PROPIEDAD INMOBILIARIA;
*FOR THE THIRD REAL ESTATE PROPERTY;

gen dprop3=0;

replace dprop3= dprop3+p2_55_3_1 if (p2_51_3>=1 & p2_51_3~=. & p2_55_3_1>0 & p2_55_3_1~=.);

replace dprop3= dprop3+ p2_55_3_2 if (p2_51_3>=2 & p2_51_3~=. & p2_55_3_2>0 & p2_55_3_2~=.);

replace dprop3= dprop3+ p2_55_3_3  if (p2_51_3>=3 & p2_51_3~=. & p2_55_3_3>0 & p2_55_3_3~=.);


*PARA EL RESTO DE PROPIEDADES INMOBILIARIAS CUANDO HAY MAS DE TRES;
*FOR THE REST OF REAL ESTATE PROPERTIES WHEN THESE ARE MORE THAN THREE;

gen dprop4=0;

replace dprop4= dprop4+p2_55_4 if (p2_55_4>0 & p2_55_4~=.);

forvalues i=1(1)4{;
rename dprop`i' vdebtprop`i';
};

label var vdebtprop1 "value of the outstanding debts from loans used to purchase other real estate property #1";
label var vdebtprop2 "value of the outstanding debts from loans used to purchase other real estate property #2";
label var vdebtprop3 "value of the outstanding debts from loans used to purchase other real estate property #3";
label var vdebtprop4 "value of the outstanding debts from loans used to purchase other real estate properties #4";


*CONSIDERANDO CONJUNTAMENTE TODAS LAS PROPIEDADES INMOBILIARIAS DIFERENTES DE LA VIVIENDA PRINCIPAL;
*CONSIDERING ALL REAL ESTATE PROPERTIES DIFFERENT FROM THE MAIN RESIDENCE;

gen deuoprop= vdebtprop1+ vdebtprop2+ vdebtprop3+ vdebtprop4 ; 
rename deuoprop vdebtothprop;
label var vdebtothprop "value of the outstanding debts from loans used to purchase other real estate properties";

*DEUDAS PENDIENTES DE PRESTAMOS SOLICITADOS PARA LA ADQUISICION DE LA VIVIENDA PRINCIPAL CON GARANTIA HIPOTECARIA;
*OUTSTANDING DEBTS FROM LOANS WITH MORTGAGE GUARANTEE USED FOR THE PURCHASE OF THE MAIN RESIDENCE;

*Para calcular la proporción de hogares que tienen deudas pendientes de préstamos CON garantía hipotecaria solicitados para la adquisición de la vivienda principal, generamos una nueva variable;
*To obtain the percentage of households that have outstanding debts from loans with mortgage guarantee used for the purchase of the main residence, 
* we generate a new variable;

gen dpdtehipo = (p2_9_1==1|p2_9_2==1|p2_9_3==1|p2_9_4==1);
rename dpdtehipo mortgmresid;
label var mortgmresid " have mortgage for the purchase of the main residence";

*Para calcular el valor de las deudas pendientes de préstamos CON garantía hipotecaria solicitados para la adquisición de la vivienda principal, generamos una nueva variable;
*To obtain the value of the outstanding debts from loans with mortgage guarantee used for the purchase of the main residence, we generate a new variable;

gen deuhipv =0;

replace deuhipv= deuhipv + p2_12_1 if (p2_8a>=1 & p2_8a~=. & p2_9_1==1 & p2_12_1>0 & p2_12_1~=.);

replace deuhipv = deuhipv + p2_12_2 if (p2_8a>=2 & p2_8a~=. & p2_9_2==1 &  p2_12_2>0 & p2_12_2~=.);

replace deuhipv= deuhipv +p2_12_3  if (p2_8a>=3 & p2_8a~=. & p2_9_3==1 &  p2_12_3>0 & p2_12_3~=.);

replace deuhipv= deuhipv +p2_12_4  if (p2_8a>3 & p2_8a~=. & p2_8a~=. & p2_9_4==1 &  p2_12_4>0 & p2_12_4~=.);

rename deuhipv vmortgmresid;
label var vmortgmresid "value of outstanding mortgages for the purchase of the main residence";


*OTRAS DEUDAS PENDIENTES NO ASOCIADAS A LA ADQUISICION DE ACTIVOS INMOBILIARIOS;
*OTHER OUTSTANDING DEBT NOT RELATED TO THE PURCHASE OF REAL ESTATE ASSETS;

*DEUDAS PENDIENTES DE PRESTAMOS HIPOTECARIOS Y OTROS PRESTAMOS CON GARANTIA REAL;
*OUTSTANDING DEBTS FROM MORTGAGES AND OTHER SECURED LOANS);

*Para calcular la proporción de hogares que tienen deudas pendientes por prestamos hipotecarios y otros préstamos con garantía real generamos una nueva variable;
*To obtain the percentage of households that have outstanding debts from mortgages and other secured loans we generate a new variable;

gen hipo=(p3_2_1==1| p3_2_2==1| p3_2_3==1| p3_2_4==1|p3_2_5==1| p3_2_6==1| p3_2_7==1| p3_2_8==1|
p3_2_1==2| p3_2_2==2| p3_2_3==2| p3_2_4==2|p3_2_4==2|p3_2_5==2| p3_2_6==2| p3_2_7==2| p3_2_8==2|
p3_2_1==10| p3_2_2==10| p3_2_3==10| p3_2_4==10|p3_2_5==10| p3_2_6==10| p3_2_7==10| p3_2_8==10);


rename hipo mortgoth;
label var mortgoth "have mortgage for other porpuses";

*Para calcular el valor de las deudas pendientes por prestamos hipotecarios y otros préstamos con garantía real generamos una nueva variable;
*To obtain the value of the outstanding debts from mortgages and other loans with real guarantee we generate a new variable;

gen phipo=0;

replace phipo = phipo +p3_6_1 if ((p3_2_1==1|p3_2_1==2) & p3_6_1>0 & p3_6_1~=.);

replace phipo = phipo +p3_6_2 if ((p3_2_2==1| p3_2_2==2) & p3_6_2>0 & p3_6_2~=.);

replace phipo = phipo +p3_6_3 if ((p3_2_3==1| p3_2_3==2)  & p3_6_3>0 & p3_6_3~=.);

replace phipo = phipo +p3_6_4 if ((p3_2_4==1| p3_2_4==2) & p3_6_4>0 & p3_6_4~=.);

replace phipo = phipo +p3_6_5 if ((p3_2_5==1| p3_2_5==2) & p3_6_5>0 & p3_6_5~=.);

replace phipo = phipo +p3_6_6 if ((p3_2_6==1| p3_2_6==2) & p3_6_6>0 & p3_6_6~=.);

replace phipo = phipo +p3_6_7 if ((p3_2_7==1| p3_2_7==2) & p3_6_7>0 & p3_6_7~=.);

replace phipo = phipo +p3_6_8 if ((p3_2_8==1| p3_2_8==2) & p3_6_8>0 & p3_6_8~=.);

rename phipo vmortgoth;
label var vmortgoth "value of outstanding mortgages for other purposes";

*Variable capturing any kind of mortgage or secure debt ;
gen mortgage =0;
replace mortgage=1 if mortgoth==1 | mortgmresid==1;

*DEUDAS PENDIENTES DE PRESTAMOS PERSONALES;
*OUTSTANDING DEBTS FROM PERSONAL LOANS;

*Para calcular la proporción de hogares que tienen deudas pendientes por prestamos personales generamos una nueva variable;
*To obtain the percentage of households that have outstanding debts from personal loans we generate a new variable;

gen perso=(p3_2_1==3| p3_2_2==3| p3_2_3==3| p3_2_4==3|p3_2_5==3| p3_2_6==3| p3_2_7==3| p3_2_8==3);
rename perso personal;
label var personal "have outstanding debts from personal loans";

*Para calcular el valor de las deudas pendientes por prestamos personales generamos una nueva variable;
*To obtain the value of the outstanding debts from personal loans we generate a new variable;

gen pperso=0;

replace pperso = pperso +p3_6_1 if (p3_2_1==3 & p3_6_1>0 & p3_6_1~=.);
replace pperso = pperso +p3_6_2 if (p3_2_2==3 & p3_6_2>0 & p3_6_2~=.);
replace pperso = pperso +p3_6_3 if (p3_2_3==3 & p3_6_3>0 & p3_6_3~=.);
replace pperso = pperso +p3_6_4 if (p3_2_4==3 & p3_6_4>0 & p3_6_4~=.);
replace pperso = pperso +p3_6_5 if (p3_2_5==3 & p3_6_5>0 & p3_6_5~=.);
replace pperso = pperso +p3_6_6 if (p3_2_6==3 & p3_6_6>0 & p3_6_6~=.);
replace pperso = pperso +p3_6_7 if (p3_2_7==3 & p3_6_7>0 & p3_6_7~=.);
replace pperso = pperso +p3_6_8 if (p3_2_8==3 & p3_6_8>0 & p3_6_8~=.);

rename pperso vpersonal;
label var vpersonal "value of personal loans";


*DEUDAS PENDIENTES CON TARJETAS DE CREDITO;
*OUTSTANDING CREDIT CARD BALANCES;

*Para calcular la proporción de hogares que tienen deudas pendientes con tarjetas de credito generamos una nueva variable;
*To obtain the percentage of households that have outstanding credit card balances we generate a new variable;

gen deuda_tarj=(p8_5a>0 & p8_5a~=.);
rename deuda_tarj credcard;
label var credcard "have outstanding credit card balances";

*Para calcular el valor de las deudas pendientes con tarjetas de credito generamos una nueva variable;
*To obtain the value of outstanding credit card balances we generate a new variable;

gen ptmos_tarj=0;

replace ptmos_tarj= p8_5a if (p8_5a>0 & p8_5a~=.);
rename ptmos_tarj vcredcard;
label var vcredcard "value of outstanding credit card balances";



*OTRAS DEUDAS;
*OTHER DEBTS;

*Para calcular la proporción de hogares que tienen otras deudas pendientes generamos una nueva variable;
*To obtain the percentage of households that have other outstanding debts we generate a new variable;

gen otrasd=(p3_2_1==4| p3_2_2==4| p3_2_3==4| p3_2_4==4| p3_2_5==4| p3_2_6==4| p3_2_7==4| p3_2_8==4|p3_2_1==5| p3_2_2==5| p3_2_3==5| p3_2_4==5| p3_2_5==5|
 p3_2_6==5| p3_2_7==5| p3_2_8==5| p3_2_1==6| p3_2_2==6| p3_2_3==6| p3_2_4==6| p3_2_5==6| p3_2_6==6| p3_2_7==6| p3_2_8==6| p3_2_1==7| p3_2_2==7| p3_2_3==7|
 p3_2_4==7| p3_2_5==7| p3_2_6==7| p3_2_7==7| p3_2_8==7| p3_2_1==8| p3_2_2==8| p3_2_3==8| p3_2_4==8| p3_2_5==8| p3_2_6==8| p3_2_7==8| p3_2_8==8| p3_2_1==9|
 p3_2_2==9| p3_2_3==9| p3_2_4==9| p3_2_5==9| p3_2_6==9| p3_2_7==9| p3_2_8==9| p3_2_1==97| p3_2_2==97| p3_2_3==97| p3_2_4==97 | p3_2_5==97| p3_2_6==97| 
 p3_2_7==97| p3_2_8==97);
rename otrasd othdebt;
label var othdebt "households that have other outstanding debt";


*Para calcular el valor de las otras deudas pendientes generamos una nueva variable;
*To obtain the value of the other outstanding debts we generate a new variable;

gen potrasd =0;

replace potrasd = potrasd +p3_6_1 if ((p3_2_1==4| p3_2_1==5| p3_2_1==6| p3_2_1==7| p3_2_1==8|p3_2_1==9|
p3_2_1==97) & p3_6_1>0 & p3_6_1~=.);
replace potrasd = potrasd +p3_6_2 if ((p3_2_2==4| p3_2_2==5|  p3_2_2==6| p3_2_2==7| p3_2_2==8|p3_2_2==9|
p3_2_2==97) & p3_6_2>0 & p3_6_2~=.);
replace potrasd = potrasd +p3_6_3 if ((p3_2_3==4| p3_2_3==5| p3_2_3==6| p3_2_3==7| p3_2_3==8|p3_2_3==9|
p3_2_3==97) & p3_6_3>0 & p3_6_3~=.);
replace potrasd = potrasd +p3_6_4 if ((p3_2_4==4| p3_2_4==5| p3_2_4==6| p3_2_4==7| p3_2_4==8|p3_2_4==9|
p3_2_4==97) & p3_6_4>0 & p3_6_4~=.);
replace potrasd = potrasd +p3_6_5 if ((p3_2_5==4| p3_2_5==5| p3_2_5==6| p3_2_5==7| p3_2_5==8|p3_2_5==9|
p3_2_5==97) & p3_6_5>0 & p3_6_5~=.);
replace potrasd = potrasd +p3_6_6 if ((p3_2_6==4| p3_2_6==5| p3_2_6==6| p3_2_6==7| p3_2_6==8|p3_2_6==9|
p3_2_6==97) & p3_6_6>0 & p3_6_6~=.);
replace potrasd = potrasd +p3_6_7 if ((p3_2_7==4| p3_2_7==5| p3_2_7==6| p3_2_7==7| p3_2_7==8|p3_2_7==9|
p3_2_7==97) & p3_6_7>0 & p3_6_7~=.);
replace potrasd = potrasd +p3_6_8 if ((p3_2_8==4| p3_2_8==5| p3_2_8==6| p3_2_8==7| p3_2_8==8|p3_2_8==9|
p3_2_8==97) & p3_6_8>0 & p3_6_8~=.);

rename potrasd vothdebt;
label var vothdebt "value of the other outstanding debts";




******************************************************************************************************;
******************************************************************************************************;

*                          R A N K I N G     A: NATURE OF THE DEBT									 *;

******************************************************************************************************;
******************************************************************************************************;
gen housesec=0;
gen houseunsec=0;
gen othsecured=0;
gen consumer=0;
gen rest=0;

gen vhousesec=0;
gen vhouseunsec=0;
gen vothsecured=0;
gen vconsumer=0;
gen vrest=0;

replace vhousesec=vhousesec+p2_55_4 if p2_55_4!=. /*Consider as secured, all debts attached to fourth real state properties in advanced */;

forvalues i=1(1)4 {;
replace housesec=1 if p2_9_`i'<=2;
replace vhousesec=vhousesec+p2_12_`i' if p2_9_`i'<=2; 
replace houseunsec=1 if p2_9_`i'>2 & p2_9_`i'<=97;
replace vhouseunsec=vhouseunsec+p2_12_`i' if p2_9_`i'>2 & p2_9_`i'<=97;
};

forvalues i=1(1)3 {;
		forvalues s=1(1)3 {; 
		replace housesec=1 if p2_52_`i'_`s'<=2;
		replace vhousesec=vhousesec+p2_55_`i'_`s' if  p2_52_`i'_`s'<=2;
		replace houseunsec=1 if p2_52_`i'_`s'>2 & p2_52_`i'_`s'<=97;
		replace vhouseunsec=vhousesec+p2_55_`i'_`s' if  p2_52_`i'_`s'>2 & p2_52_`i'_`s'<=97;
};
};

forvalues i=1(1)8 {;
replace othsecured=1 if p3_2_`i'<=2;
replace vothsecured=vothsecured+p3_6_`i' if p3_2_`i'<=2;
replace consumer=1 if p3_2_`i'==3;
replace vconsumer=vconsumer+p3_6_`i' if p3_2_`i'==3;
replace rest=1 if p3_2_`i'>3 & p3_2_`i'<=97;
replace vrest=vrest+p3_6_`i' if p3_2_`i'>3 & p3_2_`i'<=97;

};
******************************************************************************************************;
******************************************************************************************************;

*                          R A N K I N G     B: OBJECIVE OF THE DEBT									 *;

******************************************************************************************************;
******************************************************************************************************;

gen housing=0;
*gen carloan=0;
gen busloan=0;
gen restbis=0;

replace housing=1 if housesec==1;
replace restbis=1 if houseunsec==1;
forvalues i=1(1)8 {;
*replace carloan=1 if p3_3_`i'==2;
replace busloan=1 if p3_3_`i'==12;
replace housing=1 if p3_3_`i'==14 & p3_2_`i'<=2;
replace restbis=1 if p3_3_`i'==1 | p3_3_`i'==2 | p3_3_`i'==3 | p3_3_`i'==4 | p3_3_`i'==34 | p3_3_`i'==5 | p3_3_`i'==6 | p3_3_`i'==7 | p3_3_`i'==8 | p3_3_`i'==9 |
						p3_3_`i'==10 | p3_3_`i'==11 | p3_3_`i'==13 | (p3_3_`i'==14 & p3_2_`i'>2) | p3_3_`i'==15 | p3_3_`i'==97;
};

gen vhousing=0;
*gen vcarloan=0;
gen vbusloan=0;
gen vrestbis=0;

replace vhousing=vhousesec;
replace vrestbis=vhouseunsec;
forvalues i=1(1)8 {;
*replace vcarloan=vcarloan + p3_6_`i' if p3_3_`i'==2;
replace vbusloan=vbusloan + p3_6_`i'  if p3_3_`i'==12;
replace vhousing=vhousing + p3_6_`i' if p3_3_`i'==14 & p3_2_`i'<=2;
replace vrestbis=vrestbis + p3_6_`i' if p3_3_`i'==1 | p3_3_`i'==2 | p3_3_`i'==3 | p3_3_`i'==4 | p3_3_`i'==34 | p3_3_`i'==5 | p3_3_`i'==6 | p3_3_`i'==7 | p3_3_`i'==8 | p3_3_`i'==9 |
						p3_3_`i'==10 | p3_3_`i'==11 | p3_3_`i'==13 | (p3_3_`i'==14 & p3_2_`i'>2) | p3_3_`i'==15 | p3_3_`i'==97;;
};

foreach var in vhousing vbusloan vcredcard vrestbis {;
replace `var'=`var'/acpi*100;
};

 ******************* INTEREST RATES *************************;
* Main residence;
forvalues i=1(1)4{;
*rename p2_9_`i' loantypemresid_`i' /* 1-mortgage, 2- othsecured, 3- personal, 4- credit line, 5- deferred, 6- advances, 7- friends family, 97- other, 98- don't know missing */;
rename p2_13_`i' loanratemresid_`i';
rename p2_14_`i' loanfixmresid_`i';
replace loanfixmresid_`i'=1 if loanfixmresid_`i'==22;
replace loanfixmresid_`i'=0 if loanfixmresid_`i'==11;
};

* Other properties (up to 3 additional properties and 3 loans for each one);
forvalues a=1(1)3{ /*property*/;
forvalues i=1(1)3{ /*loan*/;

*rename p2_52_`a'_`i' loantypeothprop_`a'_`i' /* 1-mortgage, 2- othsecured, 3- personal, 4- credit line, 5- deferred, 6- advances, 7- friends family, 97- other, 98- don't know missing */;
rename p2_56_`a'_`i' loanrateothprop_`a'_`i';
rename p2_57_`a'_`i' loanfixothprop_`a'_`i';
replace loanfixothprop_`a'_`i'=1 if loanfixothprop_`a'_`i'==22;
replace loanfixothprop_`a'_`i'=0 if loanfixothprop_`a'_`i'==11;
};
};


* Other loans;
forvalues i=1(1)8{;
*rename p3_2_`i' loantypeother_`i' /* 1-mortgage, 2- othsecured, 3- personal, 4- credit line, 5- deferred, 6- advances, 7- friends family, 97- other, 98- don't know missing */;
rename p3_7_`i' loanrateother_`i';
rename p3_8_`i' loanfixother_`i';
replace loanfixother_`i'=1 if loanfixother_`i'==22;
replace loanfixother_`i'=0 if loanfixother_`i'==11;
};

* Credit card;
rename p8_5c int_credcard;

*************************** INTEREST RATES *******************************;
******* Housing ********;
gen int_housing=0;
forvalues i=1(1)4{;
replace int_housing=int_housing+loanratemresid_`i'*p2_12_`i' if p2_9_`i'<=2; 
};

forvalues a=1(1)3 {;
forvalues i=1(1)3 {;
replace int_housing=int_housing+loanrateothprop_`a'_`i'*p2_55_`a'_`i' if  p2_52_`a'_`i'<=2;
};
};

forvalues i=1(1)8{;
replace int_housing=int_housing+loanrateother_`i'*p3_6_`i' if p3_3_`i'==14 & p3_2_`i'<=2;
};
replace p2_55_4=0 if p2_55_4==.;
replace int_housing=int_housing/(vhousing-p2_55_4);

******** Business *******;
gen int_busloan=0;
forvalues i=1(1)8{;
replace int_busloan=int_busloan+loanrateother_`i'*p3_6_`i' if p3_3_`i'==12;
};

replace int_busloan=int_busloan/vbusloan;

********* Other *********;
gen int_restbis=0;
forvalues i=1(1)4{;
replace int_restbis=int_restbis+loanratemresid_`i'*p2_12_`i' if p2_9_`i'>2 & p2_9_`i'<=97; 
};

forvalues a=1(1)3 {;
forvalues i=1(1)3 {;
replace int_restbis=int_restbis+loanrateothprop_`a'_`i'*p2_55_`a'_`i' if  p2_52_`a'_`i'>2 & p2_52_`a'_`i'<=97;
};
};

forvalues i=1(1)8{;
replace int_restbis=int_restbis+loanrateother_`i'*p3_6_`i'  if p3_3_`i'==1 | p3_3_`i'==2 | p3_3_`i'==3 | p3_3_`i'==4 | p3_3_`i'==34 | p3_3_`i'==5 | p3_3_`i'==6 | p3_3_`i'==7 | p3_3_`i'==8 | p3_3_`i'==9 |
						p3_3_`i'==10 | p3_3_`i'==11 | p3_3_`i'==13 | (p3_3_`i'==14 & p3_2_`i'>2) | p3_3_`i'==15 | p3_3_`i'==97;
};

replace int_restbis=int_restbis/vrestbis;

*************** Debt Portfolio Structure ***************;
/* Housing (debt 1), busloan (portfdebt2), Credcard (debt 3), Rest (debt 4)*/; 


******* ONE DEBT ********************************************************************;
gen portfdebt1=0;
replace portfdebt1=1 if housing==1 & busloan==0 & credcard==0 & restbis==0;

gen portfdebt2=0;
replace portfdebt2=1 if housing==0 & busloan==1 & credcard==0 & restbis==0;

					
gen portfdebt3=0;
replace portfdebt3=1 if housing==0 & busloan==0 & credcard==1 & restbis==0;

gen portfdebt4=0;
replace portfdebt4=1 if housing==0 & busloan==0 & credcard==0 & restbis==1;


******* TWO DEBTS ********************************************************************;
gen portfdebt12=0;
replace portfdebt12=1 if housing==1 & busloan==1 & credcard==0 & restbis==0;

gen portfdebt13=0;
replace portfdebt13=1 if housing==1 & busloan==0 & credcard==1 & restbis==0;

gen portfdebt14=0;
replace portfdebt14=1  if housing==1 & busloan==0 & credcard==0 & restbis==1;

gen portfdebt23=0;
replace portfdebt23=1  if housing==0 & busloan==1 & credcard==1 & restbis==0;

gen portfdebt24=0;
replace portfdebt24=1  if housing==0 & busloan==1 & credcard==0 & restbis==1;


gen portfdebt34=0;
replace portfdebt34=1  if housing==0 & busloan==0 & credcard==1 & restbis==1;


**********THREE DEBTS ********************************************************************;
gen portfdebt123=0;
replace portfdebt123=1  if housing==1 & busloan==1 & credcard==1 & restbis==0;

gen portfdebt124=0;
replace portfdebt124=1  if housing==1 & busloan==1 & credcard==0 & restbis==1;

gen portfdebt134=0;
replace portfdebt134=1  if housing==1 & busloan==0 & credcard==1 & restbis==1;

gen portfdebt234=0;
replace portfdebt234=1  if housing==0 & busloan==1 & credcard==1 & restbis==1;

********* FOUR DEBTS *********************************************************************;
gen portfdebt1234=0;
replace portfdebt1234=1  if housing==1 & busloan==1 & credcard==1 & restbis==1;
******************************************************************************************************;



*ALGUN TIPO DE DEUDA PENDIENTE;
*SOME TYPE OF OUTSTANDING DEBT;

*Para calcular la proporción de hogares que tienen algún tipo de deuda pendiente generamos una nueva variable;
*To obtain the percentage of households that have some type of outstanding debt we generate a new variable;

gen adeuda= (debtmresid==1| debtothprop==1| p3_1>0 | credcard==1);
rename adeuda anydebt;
label var anydebt "have some type of outstanding debt";

*Para calcular el valor de las deudas pendientes generamos una nueva variable;
*To obtain the value of the outstanding debt we generate a new variable;

gen vdeuda= vdebtmresid + vdebtothprop+ vmortgoth+ vpersonal+ vothdebt + vcredcard;
rename vdeuda vdebt;
label var vdebt "value of the outstanding debt";

foreach var in portfdebt1 portfdebt2 portfdebt3 portfdebt4 portfdebt12 portfdebt13 portfdebt14 portfdebt23 
 portfdebt24 portfdebt34 portfdebt123 portfdebt124 portfdebt134 portfdebt234 portfdebt1234 {;
 
 gen v`var'=.;
 replace v`var'=vdebt if `var'==1;
 
 };
 

*VARIABLES DE RIQUEZA TOTAL Y RIQUEZAS INTERMEDIAS;
*TOTAL AND INTERMEDIATE WEALTH VARIABLES;


*ACTIVOS REALES;
*REAL ASSETS;

gen actreales=0;
replace actreales=actreales+vmresid if (vmresid>0 & vmresid~=.);
replace actreales=actreales+vothprop if (vothprop>0 & vothprop~=.);
replace actreales=actreales+vjewel if (vjewel>0 & vjewel~=.);
replace actreales=actreales+valhog if (valhog>0 & valhog~=.);

rename actreales rassets;
label var rassets "Value of real assets";


*ACTIVOS FINANCIEROS;
*FINANCIAL ASSETS;

gen actfinanc=0;
replace actfinanc=actfinanc+vaccount_pay if (vaccount_pay>0 & vaccount_pay~=.);
replace actfinanc=actfinanc+vlistshare if (vlistshare>0 & vlistshare~=.);
replace actfinanc=actfinanc+vunlist if (vunlist>0 & vunlist~=.);
replace actfinanc=actfinanc+vfixsec if (vfixsec>0 & vfixsec~=.);
replace actfinanc=actfinanc+allf if (allf>0 & allf~=.);
replace actfinanc=actfinanc+p4_43 if (p4_43>0 & p4_43~=.) /* Carteras gestionadas*/;
replace actfinanc=actfinanc+vaccount_nopay if (vaccount_nopay>0 & vaccount_nopay~=.);
replace actfinanc=actfinanc+vpenplan if (vpenplan>0 & vpenplan~=.);
replace actfinanc=actfinanc+vlifeinsur if (vlifeinsur>0 & vlifeinsur~=.);
replace actfinanc=actfinanc+vcreditor if (vcreditor>0 & vcreditor~=.);


rename actfinanc fassets;
label var fassets "Value of financial assets";

*RIQUEZA BRUTA;
*GROSS WEALTH;

gen riquezabr=0;
replace riquezabr=riquezabr+rassets+fassets;

rename riquezabr gwealth;
label var gwealth "Gross Wealth";

*RIQUEZA NETA=RIQUEZA BRUTA-DEUDAS;
*NET WEALTH=GROSS WEALTH-DEBTS;

gen riquezanet=gwealth-vdebt;
rename riquezanet nwealth;
label var nwealth "Net Wealth";

*CUADRO 6: VALOR TIPOS DE DEUDA SEGUN OBJETIVO DE LA DEUDA;
*TABLE 6: VALUE OF DEBTS BY PURPOSE OF DEBTS;

*TBD;

*Para deuda por compra vivienda principal usamos dvivpral;
*For debt originated by home purchase we use dvivpral;

*Para deuda por compra otras prop. inmobiliarias usamos deuoprop;
*For debt originated by purchase of other real estate properties we use deuoprop;

*Para deudas pendientes por el resto de deudas (garantia real, credito personal, otras deudas, deudas con tarjetas de credito) usaremos deuotros;
*For other outstanding debts (secured loans, personal loans, credit card balances and other debts) we use deuotros;

*CUADRO 8: RATIOS INDIVIDUALES DE DEUDA;
*TABLE 8: INDIVIDUAL DEBT RATIOS;

*PAGOS POR DEUDAS;
*DEBT PAYMENTS;

*Para el total de pagos por deudas generamos la variable pagodeuda;
*For total debt payments we generate the variable pagodeuda;

gen pagodeuda=0;
gen pagodeuviv=0;
gen pagodeuoprop=0;
gen pagodeusec3=0;
set output error;
forvalues j=1/4 {;
	display _newline(1) `j';
	gen np2_18_`j'=p2_18_`j';
	replace np2_18_`j'=0 if (p2_18_`j'==.|p2_18_`j'<0);
	replace pagodeuviv=pagodeuviv+np2_18_`j';
			};

forvalues j=1/8 {;
	display _newline(1) `j';
	gen np3_11_`j'=p3_11_`j';
	replace np3_11_`j'=0 if (p3_11_`j'==.|p3_11_`j'<0);
	replace pagodeusec3=pagodeusec3+np3_11_`j';
			};

forvalues m=1/3   {;
	forvalues j=1/3 {;
	display _newline(1) `m' `j';
		gen np2_61_`m'_`j'=p2_61_`m'_`j';
	replace np2_61_`m'_`j'=0 if (p2_61_`m'_`j'==.|p2_61_`m'_`j'<0);
	replace pagodeuoprop=pagodeuoprop+np2_61_`m'_`j';
			};
};
set output proc;

gen np2_61_4=p2_61_4;
replace np2_61_4=0 if (p2_61_4==. | p2_61_4<0);
replace pagodeuoprop=pagodeuoprop+np2_61_4;

gen np8_5b=p8_5b;
replace np8_5b=0 if (p8_5b==. | p8_5b<0);
gen pagotarjeta=np8_5b;
	
replace pagodeuda=pagodeuviv+pagodeuoprop+pagodeusec3 + pagotarjeta;


rename pagodeuda paydebt;
label var paydebt "Monthly total debt payments";
rename pagodeuviv paydresid;
label var paydresid "Monthly residential debt payments";
rename pagodeuoprop payothprop;
label var payothprop "Monthly other properties debt payments";
rename pagodeusec3 paypersonal;
label var paypersonal "Monthly personal debt payments";

*CUADRO 9: GASTO EN BIENES DURADEROS Y NO DURADEROS Y TENENCIA DE BIENES DURADEROS;
*TABLE 9: EXPENDITURE ON NON-DURABLE AND DURABLE GOODS AND HOLDINGS OF DURABLE GOODS;

*1.-GASTO ANUAL BIENES VARIOS (% y mediana);
*1.-ANNUAL EXPENDITURE ON DIFFERENT GOODS (% and median);

*Gasto anual en Alimentacion;
*Annual expenditure on Food;

gen frec=12 if p9_2b==2;
replace frec=12*4.3 if p9_2b==1;
gen alim=0;
replace alim=alim+(p9_2*frec) if p9_2>0;
rename alim food;
label var food "Annual expenditure on Food";

*Gasto anual en Otros bienes no duraderos;
*Annual expenditure on Other non-durable goods;

gen nodur=0;
replace nodur=nodur+ (p9_1*12)-food if p9_1>0;
label var nodur "Annual expenditure on Other non-durable goods";

*Gasto anual en vehiculos (si/no y valor);
*Annual expenditure on vehicles (yes/no and value);

*Para decisión adquisición vehículos;
*For the decision to buy vehicles;

gen gvehic=(p2_73==1 | p2_77==1);
rename gvehic vehic;
label var vehic "household purchased a vehicle that year";

*Para valor adquisicion vehículos;
*For the value of vehicles purchased;

gen gimpvehic=0;
replace gimpvehic=gimpvehic+p2_74 if (p2_74>0 & p2_74~=.);
replace gimpvehic=gimpvehic+p2_78 if (p2_78>0 & p2_78~=.);
rename gimpvehic vvehicle;
label var vvehicle "value of vehicles purchased";

*Gasto anual en Otros bienes duraderos (si/no y valor);
*Annual expenditure on Other durable goods (yes/no and value);


*Para decisión adquisición bienes duraderos utilizamos la p2_69;
*For the decision to buy durable goods we use the variable p2_69;

*Para valor adquisicion bienes duraderos usamos p2_70;
*For the value of durable goods purchases we use p2_70;


*2.- PARA TENENCIA DURADEROS (% Y MEDIANA);
*2.- FOR HOLDINGS OF DURABLE GOODS (% AND MEDIAN);

*Tenencia vehiculos;
*Holding of vehicles;

*Proporcion con vehiculos;
*Percentage with vehicles;

gen tvehic=(p2_72>0|p2_76>0);

*Mediana para los que tienen;
*Median for the ones who have; 

gen timpvehic=0;
replace timpvehic = timpvehic + p2_75 if (p2_72>0 & p2_75>0 & p2_75~=.);
replace timpvehic = timpvehic + p2_79 if ( p2_76>0 &  p2_79>0 & p2_79~=.);

*Tenencia Otros bienes duraderos;
*Holding of Other durable goods;

*Para valor tenencia bienes duraderos usamos p2_71;
*For the value of durable goods holdings we use p2_71;


*VARIABLES DE CARACTERISTICAS DE LOS HOGARES QUE FIGURAN EN LOS CUADROS;
*VARIABLES OF HOUSEHOLD CHARACTERISTICS THAT APPEAR IN THE TABLES;

*1.- DEFINICIÓN DE PERCENTILES (i) RENTA TOTAL HOGAR Y (ii) RIQUEZA NETA;
*1.- DEFINITION OF PERCENTILES (i) HOUSEHOLD TOTAL INCOME AND (ii) NET WEALTH; 
rename renthog hhincome /* annual 2001 for 2002 wave, 2004 (2005 wave), 2007 (2008 wave) */;
_pctile hhincome [pweight=facine3], p(20,40,60,80,90);
return list;

gen percrent=1 if (hhincome<r(r1));
replace percrent=2 if (hhincome>=r(r1) & hhincome<r(r2));
replace percrent=3 if (hhincome>=r(r2) & hhincome<r(r3));
replace percrent=4 if (hhincome>=r(r3) & hhincome<r(r4));
replace percrent=5 if (hhincome>=r(r4) & hhincome<r(r5));
replace percrent=6 if  hhincome>=r(r5);


_pctile nwealth [pweight=facine3], p(25,50,75,90);
return list;

gen percriq=1 if (nwealth<r(r1));
replace percriq=2 if (nwealth>=r(r1) & nwealth<r(r2));
replace percriq=3 if (nwealth>=r(r2) & nwealth<r(r3));
replace percriq=4 if (nwealth>=r(r3) & nwealth<r(r4));
replace percriq=5 if  nwealth>=r(r4);

gen percriq25=1 if nwealth==r(r1);
gen percriq50=1 if nwealth==r(r2);
gen percriq75=1 if nwealth==r(r3);

foreach var in vhousing vbusloan vcredcard vrestbis {;
gen nwealth_`var'=nwealth +`var';

gen percriq_`var'25=1 if nwealth_`var'==r(r1);
gen percriq_`var'50=1 if nwealth_`var'==r(r2);
gen percriq_`var'75=1 if nwealth_`var'==r(r3);
};
*2.- NOMBRE Y CODIFICACIÓN DE LAS VARIABLES QUE RECOGEN CARACTERÍSTICAS SOCIO-DEMOGRÁFICAS DEL HOGAR QUE APARECEN EN LOS CUADROS;
*2.- NAME AND CODING OF THE VARIABLES THAT CONTAIN HOUSEHOLDS SOCIO-DEMOGRAPHIC CHARACTERISTICS THAT APPEAR IN THE TABLES;

*EDAD DEL CABEZA DE FAMILIA;
*AGE OF HOUSEHOLD HEAD;
*bage: toma valores 1 a 6, <35, >34 & <45, >44 & <55, >54 & <65, >64 & <75, >74;
*bage: takes values 1 to 6, <35, >34 & <45, >44 & <55, >54 & <65, >64 & <75, >74;

*SITUACION LABORAL DEL CABEZA DE FAMILIA;
*LABOUR MARKET SITUATION OF HOUSEHOLD HEAD;
*nsitlabdom: toma valores 1 a 4, empleado por cuenta ajena, empleado por cuenta propia, jubilado, otro tipo de inactivo o parado;
*nsitlabdom: takes values 1 to 4, employee, self-employed, retired, other type of economic inactivity or unemployed;

*NIVEL DE EDUCACION DEL CABEZA DE FAMILIA;
*LEVEL OF EDUCATION OF HOUSEHOLD HEAD;
*neducdom: toma valores 1 a 3, inferior a bachillerato, bachillerato, estudios universitarios;
*neducdom: takes values 1 to 3, below secondary education, secondary education, University education;

*REGIMEN DE TENENCIA DE LA VIVIENDA PRINCIPAL;
*STATUS OF MAIN RESIDENCE;
*np2_1: toma valores 1 y 0, propiedad, otros regímenes de tenencia;
*np2_1: takes values 1 and 0, ownership, other;


*NUMERO DE ADULTOS EN EL HOGAR TRABAJANDO;
*NUMBER OF ADULT HOUSEHOLD MEMBERS WORKING;
*nnumadtrab: toma valores 0 a 3, ninguno, uno, dos, tres o más;
*nnumadtrab: takes values 0 to 3, none, one, two, three or more;


*NUMERO DE MIEMBROS EN EL HOGAR;
*NUMBER OF HOUSEHOLD MEMBERS;
*np1: toma valores 1 a 5, uno, dos, tres, cuatro, cinco o más.
*np1: takes values 1 to 5, one, two, three, four, five or more.
	

**** Reference person (designed by the household) variables ****;
/* From questionnaire: "The reference person is the person, or one of the persons, responsible for the accommodation. It will normally be the person in the 
household who chiefly deals with the financial issues." */;

**** Reference person (designed by the household) variables ****;
/* From questionnaire: "The reference person is the person, or one of the persons, responsible for the accommodation. It will normally be the person in the 
household who chiefly deals with the financial issues." */;

rename p1 members /* Number of household members */;



forvalues i = 1(1)9 {;
	rename p1_1_`i' sex`i' /* Male (1), Female (0)*/;
	replace sex`i'=0 if sex`i'==2;
	rename p1_2b_`i' nac`i';
	rename p1_3_`i' relref`i';
	rename p1_5_`i' educ`i' /* Education level (see questionnaire)*/;
	rename p1_7_`i' health`i' /* Health status of reference person: 1-very good, 2-good, 3-acceptable, 4-poor, 5-very poor */;
	rename p6_1c1_`i' employee`i';
	rename p6_1c2_`i' selfemployed`i';
	rename p6_1c3_`i' unemployed`i';
	rename p6_1c4_`i' retiree`i';
	rename p6_1c5_`i' disable`i';
	rename p6_1c6_`i' student`i';
	rename p6_1c7_`i' housew`i';
	rename p6_1c8_`i' oth_inact`i';
	rename p6_4_`i' typejob`i';
	gen bankjob`i'=0;
	replace bankjob`i'=1 if typejob`i'==9;
	};

	
forvalues i = 1(1)9 {;
	gen ageaux`i'=0;
	replace ageaux`i'=2017-nac`i';
	gen child`i'=0;
	replace child`i'=1 if ageaux`i'<16 ;
	};

cap drop ageaux*;

egen nchilds=rowtotal(child1-child9);
	
gen sex=0;
gen nac=0;
gen educ=0;
gen health=0;
gen employee=0;
gen selfemployed=0;
gen unemployed=0;
gen retiree=0;
gen disable=0;
gen student=0;
gen housew=0;
gen oth_inact=0;
gen bankjob=0;

* Dummy variable for university degree;
* Ordinary university degree / Training leading to an officially recognised professional specialisation;
* Postgraduate university education ;

forvalues i = 1(1)9 {;
gen univ`i'=0;
replace univ`i'=1 if educ`i'==1001 | educ`i'==1002 | educ`i'==11 | educ`i'==12;
};

gen univ=0;

/* Marital status reference person: married if any other person in the household declares to be the couple of the head */;

gen married=0;

forvalues i = 2(1)9 {;
	replace married=1 if relref`i'==2;
	};

gen couplewith=(married==1 & nchilds>0);
gen couplewithout=(married==1 & nchilds==0);
gen singlewith=(married==0 & nchilds>0);
gen singlewithout=(married==0 & nchilds==0);	
	
rename p1_4_1 marital1 /* Marital status reference person: 1-single, 2-married, 3-de facto partner 
						4-separated, 5-divorced, 6-widowed */;

/* With the information of the other members, create variables that summarize the familiar characteristics */;

*gen othcoup=0 /* to identify those hh where household head is not the reference person in the survey */;

*CRITERIUM: Take the main earner in employees. Otherwise, take the male;

* Compute wage for each member of the household;
forvalues i=1(1)9{;
replace student`i'=0 if oth_inact`i'==1 | disable`i'==1 | housew`i'==1 | unemployed`i'==1 | retiree`i'==1 | selfemployed`i'==1 | employee`i'==1;
replace oth_inact`i'=0 if disable`i'==1 | housew`i'==1 | unemployed`i'==1 | retiree`i'==1 | selfemployed`i'==1 | employee`i'==1;
replace disable`i'=0 if housew`i'==1 | unemployed`i'==1 | retiree`i'==1 | selfemployed`i'==1 | employee`i'==1;
replace housew`i'=0 if unemployed`i'==1 | retiree`i'==1 | selfemployed`i'==1 | employee`i'==1;
replace unemployed`i'=0 if retiree`i'==1 | selfemployed`i'==1 | employee`i'==1;
replace retiree`i'=0 if selfemployed`i'==1 | employee`i'==1;
replace selfemployed`i'=0 if employee`i'==1;
gen ageaux`i'=0;
replace ageaux`i'=2017-nac`i';
replace retiree`i'=1 if (housew`i'==1 | oth_inact`i'==1 | disable`i'==1 | student`i'==1) & ageaux`i'>=65 /* Take this persons as retired */;
replace housew`i'=0 if retiree`i'==1;
replace oth_inact`i'=0 if retiree`i'==1;
replace disable`i'=0 if retiree`i'==1;
replace student`i'=0 if retiree`i'==1;
};

forvalues i=1(1)9{;
	egen wage`i'=rowtotal(p6_14_`i'_*);
	gen mainearner`i'=0;
		replace employee`i'=1 if wage`i'>0 & student`i'==0 & oth_inact`i'==0 & disable`i'==0 & housew`i'==0 & 
	unemployed`i'==0 & retiree`i'==0 & selfemployed`i'==0 & employee`i'==0;
	};
	
replace mainearner1=1;

forvalues i=2(1)9{;
	replace mainearner`i'=1 if wage`i'>wage1 & relref`i'==2 & employee`i'==1;
	replace mainearner1=0   if wage`i'>wage1 & relref`i'==2 & employee`i'==1;	
	};	

forvalues i =2(1)9 {;
	gen othcoup`i'=0;
	replace othcoup`i'=1 if married==1 & sex1==0 & sex`i'==1 & relref`i'==2;	
	replace othcoup`i'=1 if married==1 & mainearner`i'==1 & relref`i'==2;
	replace othcoup`i'=1 if married==1 & (housew==1 | student==1) & 
		(unemployed`i'==1 | retiree`i'==1 | selfemployed`i'==1) & relref`i'==2 /*Take the couple when head is housewife */;
	replace sex=sex`i' if othcoup`i'==1;
	replace nac=nac`i' if othcoup`i'==1;
	replace educ=educ`i' if othcoup`i'==1;
	replace health=health`i' if othcoup`i'==1;
	replace employee=employee`i' if othcoup`i'==1;
	replace selfemployed=selfemployed`i' if othcoup`i'==1;
	replace unemployed=unemployed`i' if othcoup`i'==1;
	replace student=student`i' if othcoup`i'==1;
	replace housew=housew`i' if othcoup`i'==1;
	replace oth_inact=oth_inact`i' if othcoup`i'==1;
	replace retiree=retiree`i' if othcoup`i'==1;
	replace health=health`i' if othcoup`i'==1;
	replace univ=univ`i' if othcoup`i'==1;
	replace bankjob=bankjob`i' if othcoup`i'==1;
	};

egen othcoup=rowtotal(othcoup*);

replace sex=sex1 if othcoup==0;
replace nac=nac1 if othcoup==0;
replace educ=educ1 if othcoup==0;
replace health=health1 if othcoup==0;
replace employee=employee1 if othcoup==0;
replace selfemployed=selfemployed1 if othcoup==0;
replace retiree=retiree1 if othcoup==0;
replace disable=disable1 if othcoup==0;
replace student=student1 if othcoup==0;
replace housew=housew1 if othcoup==0;
replace oth_inact=oth_inact1 if othcoup==0;
replace unemployed=unemployed1 if othcoup==0;
replace univ=univ1 if othcoup==0;
replace bankjob=bankjob1 if othcoup==0;

/* Gen dummy to identify status of the couple */;
gen pemployee=0;
gen pselfemployed=0;
gen punemployed=0;
gen pretiree=0;
gen pdisable=0;
gen pstudent=0;
gen phousew=0;
gen poth_inact=0;
gen puniv=0;
gen pnac=0;

forvalues i=2(1)9 {;
	replace punemployed=1 if othcoup`i'==0 & unemployed`i'==1 & relref`i'==2;
	replace pemployee=1 if othcoup`i'==0 & employee`i'==1 & relref`i'==2;
	replace pretiree=1 if othcoup`i'==0 & retiree`i'==1 & relref`i'==2;
	replace pselfemployed=1 if othcoup`i'==0 & selfemployed`i'==1 & relref`i'==2;
	replace pdisable=1 if othcoup`i'==0 & disable`i'==1 & relref`i'==2;
	replace pstudent=1 if othcoup`i'==0 & student`i'==1 & relref`i'==2;
	replace phousew=1 if othcoup`i'==0 & housew`i'==1 & relref`i'==2;
	replace poth_inact=1 if othcoup`i'==0 & oth_inact`i'==1 & relref`i'==2;
	replace puniv=1 if othcoup`i'==0 & univ`i'==1 & relref`i'==2;
	replace pnac=1 if othcoup`i'==0 & nac`i'==1 & relref`i'==2;

	replace punemployed=1 if othcoup`i'==1 & unemployed1==1 & relref`i'==2;
	replace pemployee=1 if othcoup`i'==1 & employee1==1 & relref`i'==2;
	replace pretiree=1 if othcoup`i'==1 & retiree1==1 & relref`i'==2;
	replace pselfemployed=1 if othcoup`i'==1 & selfemployed1==1 & relref`i'==2;
	replace pdisable=1 if othcoup`i'==1 & disable1==1 & relref`i'==2;
	replace pstudent=1 if othcoup`i'==1 & student1==1 & relref`i'==2;
	replace phousew=1 if othcoup`i'==1 & housew1==1 & relref`i'==2;
	replace poth_inact=1 if othcoup`i'==1 & oth_inact1==1 & relref`i'==2;
	replace puniv=1 if othcoup`i'==1 & univ1==1 & relref`i'==2;
	replace pnac=1 if othcoup`i'==1 & nac1==1 & relref`i'==2;
	};
	
* Define other reference person for housew/student households: specifically, take as reference person those sons or daughters that are
*main earners;

egen maxw=rowmax(wage1 wage2 wage3 wage4 wage5 wage6 wage7 wage8 wage9);

forvalues i=2(1)9{;
		gen oth_member`i'=0;
		replace oth_member`i'=1 if (housew==1 | student==1) & wage`i'==maxw & maxw>0;
		replace employee`i'=1 if oth_member`i'==1;
		replace sex=sex`i' if oth_member`i'==1;
		*replace psex=0 if oth_member`i'==1 /* Assume has no couple */;
		replace nac=nac`i' if oth_member`i'==1;
		replace pnac=0 if oth_member`i'==1 /* Assume has no couple */;
		replace educ=educ`i' if oth_member`i'==1;
		*replace peduc=0 if oth_member`i'==1 /* Assume has no couple */;
		replace health=health`i' if oth_member`i'==1;
		*replace phealth=0 if oth_member`i'==1 /* Assume has no couple */;
		replace employee=employee`i' if oth_member`i'==1;
		replace pemployee=0 if oth_member`i'==1 /* Assume has no couple */;
		replace selfemployed=selfemployed`i' if oth_member`i'==1;
		replace pselfemployed=0 if oth_member`i'==1 /* Assume has no couple */;
		replace retiree=retiree`i' if oth_member`i'==1;
		replace pretiree=0 if oth_member`i'==1 /* Assume has no couple */;
		replace disable=disable`i' if oth_member`i'==1;
		replace pdisable=0 if oth_member`i'==1 /* Assume has no couple */;
		replace student=student`i' if oth_member`i'==1;
		replace pstudent=0 if oth_member`i'==1 /* Assume has no couple */;
		replace housew=housew`i' if oth_member`i'==1;
		replace phousew=0 if oth_member`i'==1 /* Assume has no couple */;
		replace oth_inact=oth_inact`i' if oth_member`i'==1;
		replace poth_inact=0 if oth_member`i'==1 /* Assume has no couple */;
		replace unemployed=unemployed`i' if oth_member`i'==1;
		replace punemployed=0 if oth_member`i'==1 /* Assume has no couple */;
		replace univ=univ`i' if oth_member`i'==1;
		replace puniv=0 if oth_member`i'==1 /* Assume has no couple */;
		};	


egen auxoth=rowtotal(oth_member*);
		
/* Choose other household member if there are no employees*/;
forvalues i=2(1)9{;
		gen oth2_member`i'=0;
		replace oth2_member`i'=1 if (housew==1 | student==1) & auxoth==0 & selfemployed`i'==1;
		replace selfemployed`i'=1 if oth2_member`i'==1;
		replace sex=sex`i' if oth2_member`i'==1;
		*replace psex=0 if oth_member`i'==1 /* Assume has no couple */;
		replace nac=nac`i' if oth2_member`i'==1;
		replace pnac=0 if oth2_member`i'==1 /* Assume has no couple */;
		replace educ=educ`i' if oth2_member`i'==1;
		*replace peduc=0 if oth_member`i'==1 /* Assume has no couple */;
		replace health=health`i' if oth2_member`i'==1;
		*replace phealth=0 if oth_member`i'==1 /* Assume has no couple */;
		replace employee=employee`i' if oth2_member`i'==1;
		replace pemployee=0 if oth2_member`i'==1 /* Assume has no couple */;
		replace selfemployed=selfemployed`i' if oth2_member`i'==1;
		replace pselfemployed=0 if oth2_member`i'==1 /* Assume has no couple */;
		replace retiree=retiree`i' if oth2_member`i'==1;
		replace pretiree=0 if oth2_member`i'==1 /* Assume has no couple */;
		replace disable=disable`i' if oth2_member`i'==1;
		replace pdisable=0 if oth2_member`i'==1 /* Assume has no couple */;
		replace student=student`i' if oth2_member`i'==1;
		replace pstudent=0 if oth2_member`i'==1 /* Assume has no couple */;
		replace housew=housew`i' if oth2_member`i'==1;
		replace phousew=0 if oth2_member`i'==1 /* Assume has no couple */;
		replace oth_inact=oth_inact`i' if oth2_member`i'==1;
		replace poth_inact=0 if oth2_member`i'==1 /* Assume has no couple */;
		replace unemployed=unemployed`i' if oth2_member`i'==1;
		replace punemployed=0 if oth2_member`i'==1 /* Assume has no couple */;
		replace univ=univ`i' if oth2_member`i'==1;
		replace puniv=0 if oth2_member`i'==1 /* Assume has no couple */;
		};	

gen bhealth=0;
replace bhealth=1 if health>=4;

egen auxoth2=rowtotal(oth2_member*);
	
egen aux=rowtotal(employee selfemployed unemployed retiree disable student housew oth_inact);
keep if aux==1;	

gen age=2017-nac;
replace age=age/10;

** Age dummies **;
gen age1=0;
replace age1=1 if age>=3 & age<3.5;

gen age2=0;
replace age2=1 if age>=3.5 & age<4;

gen age3=0;
replace age3=1 if age>=4 & age<4.5;

gen age4=0;
replace age4=1 if age>=4.5 & age<5;

gen age5=0;
replace age5=1 if age>=5 & age<5.5;

gen age6=0;
replace age6=1 if age>=5.5 & age<6;

gen age7=0;
replace age7=1 if age>=6 & age<6.5;

gen age8=0;
replace age8=1 if age>=6.5 & age<7;

gen age9=0;
replace age9=1 if age>=7 & age<7.6;

gen age_inst=0;
replace age_inst=1 if age1==1;
replace age_inst=2 if age2==1;
replace age_inst=3 if age3==1;
replace age_inst=4 if age4==1;
replace age_inst=5 if age5==1;
replace age_inst=6 if age6==1;
replace age_inst=7 if age7==1;
replace age_inst=8 if age8==1;
replace age_inst=9 if age9==1;

gen agesq=age^2;

gen page=2014-nac;
replace page=page/10;

** page dummies **;
gen page1=0;
replace page1=1 if page>=3 & page<3.5;

gen page2=0;
replace page2=1 if page>=3.5 & page<4;

gen page3=0;
replace page3=1 if page>=4 & page<4.5;

gen page4=0;
replace page4=1 if page>=4.5 & page<5;

gen page5=0;
replace page5=1 if page>=5 & page<5.5;

gen page6=0;
replace page6=1 if page>=5.5 & page<6;

gen page7=0;
replace page7=1 if page>=6 & page<6.5;

gen page8=0;
replace page8=1 if page>=6.5 & page<7;

gen page9=0;
replace page9=1 if page>=7 & page<7.6;

gen page_inst=0;
replace page_inst=1 if page1==1;
replace page_inst=2 if page2==1;
replace page_inst=3 if page3==1;
replace page_inst=4 if page4==1;
replace page_inst=5 if page5==1;
replace page_inst=6 if page6==1;
replace page_inst=7 if page7==1;
replace page_inst=8 if page8==1;
replace page_inst=9 if page9==1;

gen pagesq=page^2;



/* Drop multiple-unrelated households */;

egen minval=rowmin(relref*);
replace minval=0 if minval==.;

gen madult=0;
replace madult=1 if minval==9 & (year==2002 | year==2005);
replace madult=1 if minval==12 & (year==2008 | year==2011);



********************************************;
rename p2_3 instal /* Year of house purchasing (assume to be the same as instalment) */;
rename p2_4 price_a /* Purchasing price */;
rename p2_5 price_b /* Price of hypothetical sell */;


		  ******************* Application for loans (2)*****************;

rename p3_12a treject;
rename p3_12b preject;

/* Totally reject loan application (any) */;		  
gen reject=0;
replace reject=1 if treject==1;
replace reject=0 if treject==.;

forvalues i=1(1)4 {;
	rename p3_13s`i' rnoappl`i' /* Reasons of not applying for a loan */;
	};
	
forvalues i=1(1)3 {;
	rename p3_15s`i' rreject`i' /* Reasons of rejecting */;
	};
	
gen applic2=0;
replace applic2=1 if rnoappl1==.;

/* Discouraged borrowers: refuse to apply for a loan because it would be turned down (any member of the household. Exclude debt holders */;
gen discour=0;
replace discour=1 if (rnoappl1==4 | rnoappl2==4 | rnoappl3==4 | rnoappl4==4) & anydebt==0 & applic2==0;

/* Applicant: whether the household made any loan application or refused beacuse of sure rejecting */;
gen applic=0;
replace applic=1 if applic2>0 | discour==1 | anydebt==1;

/* Partially rejected loan application (any) */;
gen partrej=0;
replace partrej=1 if preject==1;
replace partrej=0 if preject==.;
		
gen totpartrej=0;
replace totpartrej=1 if (reject==1 | partrej==1);
replace totpartrej=1 if discour==1;
**replace totpartrej=0 if anydebt==1;

/* Rationed: discouraged or reject totally or partially */;
gen ration2=0;
replace ration2=1 if discour==1 | partrej==1 | reject==1;
replace ration2=0 if ration2==.;
*replace ration2=0 if anydebt==1;

/* Rationed: discouraged or totally rejected */;
gen ration=0;
replace ration=1 if discour==1 | reject==1;
replace ration=0 if ration==.;
*replace ration=0 if anydebt==1;

*replace anydebt=1 if applic==1 & anydebt==0 & ration==0 /* Applied, borrowed and repaid, and report zero borrowing */;

						   
**************** INCOME *********************;
*rename renthog hhincome /* annual 2001 for 2002 wave, 2004 (2005 wave), 2007 (2008 wave) */;
replace hhincome=hhincome/acpi*100;
gen lincome=log(1+hhincome);
replace hhincome=hhincome/10000;
gen hhincomesq=(hhincome^2)/10000;

rename mrenthog mhhincome /* month oct2002 - may2003 (2002), nov2005 - may2006 (2005), nov2008 - jun2009 (2008) */;
replace mhhincome=mhhincome/mcpi*100;
gen mhhincomesq=mhhincome^2;


************** FINANCIAL HELP FROM RELATIVES AND FRIENDS *******************;
/*monetary assistance from friends or family members outside the
household, or from a partner no longer living in the household*/;

rename p6_59 finhelp;
replace finhelp=0 if finhelp==2;

rename p6_60 amounthelp;
replace amounthelp=amounthelp/mcpi*100;

************ ARREARS *****************;

/* In the last twelve months have you had any financial
difficulties which resulted in your delaying the payment of any of
your debts? */;

gen arrears=0;
replace arrears=1 if p9_16==1;

gen arrears_bank=0;
replace arrears_bank=1 if p9_16a==1;

*replace anydebt=1 if arrears==1;
replace applic=1 if anydebt==1;
*replace ration=0 if arrears==1;
replace discour=0 if anydebt==1;

gen applic_non_disc=0;
replace applic_non_disc=1 if applic==1 & discour==0;

gen repay=.;
replace repay=1 if arrears==0 & anydebt==1;
replace repay=0 if arrears==1;

* Risk Aversion;
rename p9_11 riskaver;

gen risklot=.;
replace risklot=0 if riskaver==2 | riskaver==3 | riskaver==4;
replace risklot=1 if riskaver==1;

gen riskfair=.;
replace riskfair=0 if riskaver==1 | riskaver==3 | riskaver==4;
replace riskfair=1 if riskaver==2;

gen risksome=.;
replace risksome=0 if riskaver==1 | riskaver==2 | riskaver==4;
replace risksome=1 if riskaver==3;

gen norisk=.;
replace norisk=0 if riskaver==1 | riskaver==2 | riskaver==3;
replace norisk=1 if riskaver==4;

******** Dummies for hhincome ********;
_pctile hhincome, p(20,40,60,80);
scalar r1=r(r1);
scalar r2=r(r2);
scalar r3=r(r3);
scalar r4=r(r4);

gen hhincome1=0;
replace hhincome1=1 if hhincome<scalar(r1);

gen hhincome2=0;
replace hhincome2=1 if hhincome>=scalar(r1) & hhincome<scalar(r2);

gen hhincome3=0;
replace hhincome3=1 if hhincome>=scalar(r2) & hhincome<scalar(r3);

gen hhincome4=0;
replace hhincome4=1 if hhincome>=scalar(r3)  & hhincome<scalar(r4);

gen hhincome5=0;
replace hhincome5=1 if hhincome>scalar(r4);

gen inc_inst=0;
replace inc_inst=1 if hhincome1==1;
replace inc_inst=2 if hhincome2==1;
replace inc_inst=3 if hhincome3==1;
replace inc_inst=4 if hhincome4==1;


*********** Dummies for income II ************;
replace hhincome=hhincome*10000;

gen hh1=0;
replace hh1=1 if hhincome<=15000;
gen hh2=0;
replace hh2=1 if hhincome>15000 & hhincome<=25000;
gen hh3=0;
replace hh3=1 if hhincome>25000 & hhincome<=35000;
gen hh4=0;
replace hh4=1 if hhincome>35000 & hhincome<=45000;
gen hh5=0;
replace hh5=1 if hhincome>45000 & hhincome<=57000;
gen hh6=0;
replace hh6=1 if hhincome>57000;
*/;
gen hh_inst=0;
replace hh_inst=1 if hh1==1;
replace hh_inst=2 if hh2==1;
replace hh_inst=3 if hh3==1;
replace hh_inst=4 if hh4==1;
replace hh_inst=5 if hh5==1;
replace hh_inst=6 if hh6==1;
*replace hh_inst=7 if hh7==1;
*replace hh_inst=8 if hh8==1;
*replace hh_inst=9 if hh9==1;

replace hhincome=hhincome/10000;


*********** Dummies for nwealth ************;

replace nwealth=nwealth/acpi*100;
gen lnwealth=.;
replace lnwealth=log(1+abs(nwealth)) if nwealth>=0;
replace lnwealth=-log(1+abs(nwealth)) if nwealth<0;

gen nw1=0;
replace nw1=1 if nwealth<=10000;
gen nw2=0;
replace nw2=1 if nwealth>10000 & nwealth<=80000;
gen nw3=0;
replace nw3=1 if nwealth>80000 & nwealth<=200000;
gen nw4=0;
replace nw4=1 if nwealth>200000 & nwealth<=500000;
gen nw5=0;
replace nw5=1 if nwealth>500000;


***** Generate alternative wealth variables *****;
gen housewealth= nwealth;
replace housewealth=housewealth-vmresid/acpi*100+vdebtmresid/acpi*100 if debtmresid==1;

replace housewealth=housewealth + vdebtprop1/acpi*100 - p2_39_1*(p2_37_1/100)/acpi*100 if vdebtprop1>0;
replace housewealth=housewealth + vdebtprop2/acpi*100 - p2_39_2*(p2_37_1/100)/acpi*100 if vdebtprop2>0;
replace housewealth=housewealth + vdebtprop3/acpi*100 - p2_39_3*(p2_37_1/100)/acpi*100 if vdebtprop3>0;
replace housewealth=housewealth + vdebtprop4/acpi*100 - p2_39_4*(p2_37_1/100)/acpi*100 if vdebtprop4>0;

gen lhousingw=.;
replace lhousingw=log(1+abs(housewealth)) if housewealth>=0;
replace lhousingw=-log(1+abs(housewealth)) if housewealth<0;

gen buswealth=nwealth;
replace buswealth=buswealth-valhog/acpi*100+vbusloan;

gen lbusloanw=.;
replace lbusloanw=log(1+abs(buswealth)) if buswealth>=0;
replace lbusloanw=-log(1+abs(buswealth)) if buswealth<0;

gen cardwealth=nwealth;
replace cardwealth=cardwealth+vcredcard;

gen lcredcardw=.;
replace lcredcardw=log(1+abs(cardwealth)) if cardwealth>=0;
replace lcredcardw=-log(1+abs(cardwealth)) if cardwealth<0;

gen otherwealth=nwealth;
replace otherwealth=otherwealth-vrestbis;

gen lrestbisw=.;
replace lrestbisw=log(1+abs(otherwealth)) if otherwealth>=0;
replace lrestbisw=-log(1+abs(otherwealth)) if otherwealth<0;

*********** Dummies for housing wealth ************;

gen housingw1=0;
replace housingw1=1 if housewealth<=10000;
gen housingw2=0;
replace housingw2=1 if housewealth>10000 & housewealth<=80000;
gen housingw3=0;
replace housingw3=1 if housewealth>80000 & housewealth<=200000;
gen housingw4=0;
replace housingw4=1 if housewealth>200000 & housewealth<=500000;
gen housingw5=0;
replace housingw5=1 if housewealth>500000;

*********** Dummies for business wealth ************;

gen busloanw1=0;
replace busloanw1=1 if buswealth<=10000;
gen busloanw2=0;
replace busloanw2=1 if buswealth>10000 & buswealth<=80000;
gen busloanw3=0;
replace busloanw3=1 if buswealth>80000 & buswealth<=200000;
gen busloanw4=0;
replace busloanw4=1 if buswealth>200000 & buswealth<=500000;
gen busloanw5=0;
replace busloanw5=1 if buswealth>500000;

*********** Dummies for credit card wealth ************;

gen credcardw1=0;
replace credcardw1=1 if cardwealth<=10000;
gen credcardw2=0;
replace credcardw2=1 if cardwealth>10000 & cardwealth<=80000;
gen credcardw3=0;
replace credcardw3=1 if cardwealth>80000 & cardwealth<=200000;
gen credcardw4=0;
replace credcardw4=1 if cardwealth>200000 & cardwealth<=500000;
gen credcardw5=0;
replace credcardw5=1 if cardwealth>500000;


*********** Dummies for other debts wealth ************;

gen restbisw1=0;
replace restbisw1=1 if otherwealth<=10000;
gen restbisw2=0;
replace restbisw2=1 if otherwealth>10000 & otherwealth<=80000;
gen restbisw3=0;
replace restbisw3=1 if otherwealth>80000 & otherwealth<=200000;
gen restbisw4=0;
replace restbisw4=1 if otherwealth>200000 & otherwealth<=500000;
gen restbisw5=0;
replace restbisw5=1 if otherwealth>500000;


foreach f of var * { ;
	rename `f' `f'_imp`x' ;
} ;
rename h_2017_imp`x' h2017;
drop p6*;
save wave2017_imp`x'.dta, replace;

};
cd "H:\Mi unidad\Grant_new\EFF";
use "H:\Mi unidad\Grant_new\EFF\Imputation1\wave2017_imp1.dta";
joinby h2017 using "H:\Mi unidad\Grant_new\EFF\Imputation2\wave2017_imp2";
joinby h2017 using "H:\Mi unidad\Grant_new\EFF\Imputation3\wave2017_imp3";
joinby h2017 using "H:\Mi unidad\Grant_new\EFF\Imputation4\wave2017_imp4";
joinby h2017 using "H:\Mi unidad\Grant_new\EFF\Imputation5\wave2017_imp5";



save "H:\Mi unidad\Grant_new\wave2017.dta", replace;

erase "H:\Mi unidad\Grant_new\EFF\Imputation1\wave2017_imp1.dta";
erase "H:\Mi unidad\Grant_new\EFF\Imputation2\wave2017_imp2.dta";
erase "H:\Mi unidad\Grant_new\EFF\Imputation3\wave2017_imp3.dta";
erase "H:\Mi unidad\Grant_new\EFF\Imputation4\wave2017_imp4.dta";
erase "H:\Mi unidad\Grant_new\EFF\Imputation5\wave2017_imp5.dta";


use "H:\Mi unidad\Grant_new\wave2002.dta", clear;
append using "H:\Mi unidad\Grant_new\wave2005.dta";
append using "H:\Mi unidad\Grant_new\wave2008.dta";
append using "H:\Mi unidad\Grant_new\wave2011.dta";
append using "H:\Mi unidad\Grant_new\wave2014.dta";
append using "H:\Mi unidad\Grant_new\wave2017.dta";


cap drop year_imp1 year_imp2 year_imp3 year_imp4; 
rename year_imp5 year;
tab year, gen(ye);

rename ye1 ye2002;
rename ye2 ye2005;
rename ye3 ye2008;
rename ye4 ye2011;
rename ye5 ye2014;
rename ye6 ye2017;


********************************************************************************************;
***************************************** CREATE PANEL *************************************;
********************************************************************************************;

* Paste mariomerge.do here;

use "H:\Mi unidad\Grant_new\wave2017.dta", clear;
rename h_2014_imp1 h2014;
keep h2017 h2014;
sor h2014;
save "H:\Mi unidad\Grant_new\wave_hi_2017.dta", replace;
drop _all;

use "H:\Mi unidad\Grant_new\wave2014.dta", clear;
rename h_2011_imp1 h2011;
keep h2014 h2011;
sor h2014;
save "H:\Mi unidad\Grant_new\wave_hi_2014.dta", replace;
drop _all;

* Join 2014 and 2017 ;
u "H:\Mi unidad\Grant_new\wave_hi_2017.dta";
mer h2014 using "H:\Mi unidad\Grant_new\wave_hi_2014.dta";
tab _merge;
drop _merge;
sor h2011;
sa "H:\Mi unidad\Grant_new\wave_hi_2014_2017.dta", replace;

use "H:\Mi unidad\Grant_new\wave2011.dta", clear;
rename h_2008_imp1 h2008;
keep h2011 h2008;
*ren h_number h_2002;
sor h2011;
save "H:\Mi unidad\Grant_new\wave_hi_2011.dta", replace;


*Join 2011, 2014 and 2017 ;



u "H:\Mi unidad\Grant_new\wave_hi_2014_2017.dta";
mer h2011 using "H:\Mi unidad\Grant_new\wave_hi_2011.dta";
tab _merge;
drop _merge;
sor h2008;
sa "H:\Mi unidad\Grant_new\wave_hi_2011_2014_2017.dta", replace;


* Join 2008 to 2011,2014 and 2017;
use "H:\Mi unidad\Grant_new\wave2008.dta", clear;
rename h_2005_imp1 h2005;
keep h2008 h2005;
sor h2008;
save "H:\Mi unidad\Grant_new\wave_hi_2008.dta", replace;

merge h2008 using "H:\Mi unidad\Grant_new\wave_hi_2011_2014_2017.dta";
tab _merge;
drop _merge;
*gen hhid=_n;
sort h2011;
list if h2011==h2011[_n-1] & h2011!=.;
list if h2011==h2011[_n+1] & h2011!=.;
sor h2005;
sa "H:\Mi unidad\Grant_new\wave_hi_08_11_14_17.dta", replace;
drop _all;

* Join 2005 to 2008, 2011, 2014, 2017 and 2020;
u "H:\Mi unidad\Grant_new\wave2005.dta";
rename h_number_imp1 h2002;
keep h2005 h2002;
sor h2005;
sa "H:\Mi unidad\Grant_new\wave_hi_2005.dta", replace;

merge h2005 using "H:\Mi unidad\Grant_new\wave_hi_08_11_14_17.dta";
tab _merge;
drop _merge;
*gen hhid=_n;
sort h2002;
list if h2008==h2008[_n-1] & h2008!=.;
list if h2008==h2008[_n+1] & h2008!=.;
sa "H:\Mi unidad\Grant_new\wave_hi_05_08_11_14_17.dta", replace;
drop _all;


u "H:\Mi unidad\Grant_new\wave2002.dta";
keep h2002;
sor h2002;
sa "H:\Mi unidad\Grant_new\wave_hi_2002.dta", replace;

* Join 2002 to 2005,2008, 2011, 2014 and 2017;
merge h2002 using "H:\Mi unidad\Grant_new\wave_hi_05_08_11_14_17.dta";
tab _merge;
drop _merge;
gen hhid=_n;
sort h2005;
list if h2005==h2005[_n-1] & h2005!=.;
list if h2005==h2005[_n+1] & h2005!=.;
sa "H:\Mi unidad\Grant_new\wave_hi_02_05_08_11_14_17.dta", replace;
drop _all;

u "H:\Mi unidad\Grant_new\wave2002.dta";
sor h2002;
merge 1:m h2002 using "H:\Mi unidad\Grant_new\wave_hi_02_05_08_11_14_17.dta", keepusing(hhid) ;
cap drop wt3* ntime*  p6* p5* age_inst* page*;
keep if _merge==3;
compress;
sa "H:\Mi unidad\Grant_new\wave2002_f.dta", replace;
drop _all;


u "H:\Mi unidad\Grant_new\wave2005.dta";
keep h2005;
sor h2005;
sa "H:\Mi unidad\Grant_new\wave_hi_2005.dta", replace;

merge h2005 using "H:\Mi unidad\Grant_new\wave_hi_08_11_14_17.dta";
tab _merge;
drop _merge;
gen hhid=_n;
sort h2008;
list if h2008==h2008[_n-1] & h2008!=.;
list if h2008==h2008[_n+1] & h2008!=.;
sa "H:\Mi unidad\Grant_new\wave_hi_05_08_11_14_17.dta", replace;
drop _all;

u "H:\Mi unidad\Grant_new\wave2005.dta";
sor h2005;
merge h2005 using "H:\Mi unidad\Grant_new\EFF\EFF_2005\replicate_weights_2005.dta";
tab _merge;
drop _merge;
merge 1:m h2005 using "H:\Mi unidad\Grant_new\wave_hi_05_08_11_14_17.dta", keepusing(hhid) ;
cap drop wt3* ntime*  p6* p5* age_inst* page*;
keep if _merge==3;
sa "H:\Mi unidad\Grant_new\wave2005_f.dta", replace;
drop _all;

u "H:\Mi unidad\Grant_new\wave2008.dta";
sor h2008;
merge h2008 using "H:\Mi unidad\Grant_new\EFF\EFF_2008\replicate_weights_2008.dta";
tab _merge;
drop _merge;
merge 1:m h2008 using "H:\Mi unidad\Grant_new\wave_hi_05_08_11_14_17.dta", keepusing(hhid) ;
cap drop wt3* ntime*  p6* p5* age_inst* page*;
keep if _merge==3;
sa "H:\Mi unidad\Grant_new\wave2008_f.dta", replace;
drop _all;

u "H:\Mi unidad\Grant_new\wave2011.dta";
sor h2011;
merge h2011 using "H:\Mi unidad\Grant_new\EFF\EFF_2011\replicate_weights_2011.dta";
tab _merge;
drop _merge;
merge 1:m h2011 using "H:\Mi unidad\Grant_new\wave_hi_05_08_11_14_17.dta", keepusing(hhid) ;
cap drop wt3* ntime*  p6* p5* age_inst* page*;
keep if _merge==3;
sa "H:\Mi unidad\Grant_new\wave2011_f.dta", replace;
drop _all;

u "H:\Mi unidad\Grant_new\wave2014.dta";
sor h2014;
merge h2014 using "H:\Mi unidad\Grant_new\EFF\EFF_2014\replicate_weights_2014.dta";
tab _merge;
drop _merge;
merge 1:m h2014 using "H:\Mi unidad\Grant_new\wave_hi_05_08_11_14_17.dta", keepusing(hhid) ;
cap drop wt3* ntime*  p6* p5* age_inst* page*;
keep if _merge==3;
sa "H:\Mi unidad\Grant_new\wave2014_f.dta", replace;
drop _all;

u "H:\Mi unidad\Grant_new\wave2017.dta";
sor h2017;
merge h2017 using "H:\Mi unidad\Grant_new\EFF\EFF_2017\replicate_weights_2017.dta";
tab _merge;
drop _merge;
merge 1:m h2017 using "H:\Mi unidad\Grant_new\wave_hi_05_08_11_14_17.dta", keepusing(hhid) ;
cap drop wt3* ntime*  p6* p5* age_inst* page*;
keep if _merge==3;
sa "H:\Mi unidad\Grant_new\wave2017_f.dta", replace;
drop _all;

u "H:\Mi unidad\Grant_new\wave2002_f.dta";
append using "H:\Mi unidad\Grant_new\wave2005_f.dta";
append using "H:\Mi unidad\Grant_new\wave2008_f.dta";
append using "H:\Mi unidad\Grant_new\wave2011_f.dta";
append using "H:\Mi unidad\Grant_new\wave2014_f.dta";
append using "H:\Mi unidad\Grant_new\wave2017_f.dta";

/*;
gen totpartrej=0;
replace totpartrej=1 if (reject==1 | partrej==1);
replace totpartrej=1 if discour==1;
replace totpartrej=0 if anydebt==1;
*/;

sa "H:\Mi unidad\Grant_new\wave_all.dta", replace;

**************************************************************;
** Cross Tabs for Arrears / Applications in Different Years **;
**************************************************************;

bysort hhid: gen pnel = _N;

cap drop year_imp1 year_imp2 year_imp3 year_imp4;
iis hhid;
tis year;



cap log close;

bysort hhid: gen pnel2 = _N;

foreach var of varlist  valhog* valdeuhog* vmresid* vothprop* vjewel* vaccount_pay* vlistshare* vunlist* vfixsec* p4_31* vaccount_nopay* vpenplan*
				vlifeinsur* vpeninsur* vcreditor* vdebtmresid* vdebtprop* vmortgmresid* vmortgoth* vpersonal* vcredcard* vothdebt* p4_43* paydebt*
				paydresid* payothprop* paypersonal* food* nodur* vvehicle* timpvehic* wage* price_a* price_b* vhousesec* vhouseunsec*
				vothsecured* vconsumer* vrest* vhousing* vbusloan* vrestbis* vportfdebt*{;
				
	replace `var'=`var'/acpi_imp1*100;
	};

foreach x in 1 2 3 4 5 {;
foreach var in housing busloan credcard restbis {;
gen l`var'_imp`x'=log(1+v`var'_imp`x');
};
};

save sample_eff.dta, replace;

erase "H:\Mi unidad\Grant_new\wave_all.dta";
erase "H:\Mi unidad\Grant_new\wave_hi_02_05_08_11_14_17.dta";
erase "H:\Mi unidad\Grant_new\wave_hi_05_08_11_14_17.dta";
erase "H:\Mi unidad\Grant_new\wave_hi_08_11_14_17.dta";
erase "H:\Mi unidad\Grant_new\wave_hi_2011_2014_2017.dta";
erase "H:\Mi unidad\Grant_new\wave_hi_2014_2017.dta";
*erase "H:\Mi unidad\Grant_new\wave_hi_17.dta";
erase "H:\Mi unidad\Grant_new\wave_hi_2002.dta";
erase "H:\Mi unidad\Grant_new\wave_hi_2005.dta";
erase "H:\Mi unidad\Grant_new\wave_hi_2008.dta";
erase "H:\Mi unidad\Grant_new\wave_hi_2011.dta";
erase "H:\Mi unidad\Grant_new\wave_hi_2014.dta";
erase "H:\Mi unidad\Grant_new\wave_hi_2017.dta";
erase "H:\Mi unidad\Grant_new\wave2002.dta";
erase "H:\Mi unidad\Grant_new\wave2002_f.dta";
erase "H:\Mi unidad\Grant_new\wave2005.dta";
erase "H:\Mi unidad\Grant_new\wave2005_f.dta";
erase "H:\Mi unidad\Grant_new\wave2008.dta";
erase "H:\Mi unidad\Grant_new\wave2008_f.dta";
erase "H:\Mi unidad\Grant_new\wave2011.dta";
erase "H:\Mi unidad\Grant_new\wave2011_f.dta";
erase "H:\Mi unidad\Grant_new\wave2014.dta";
erase "H:\Mi unidad\Grant_new\wave2014_f.dta";
erase "H:\Mi unidad\Grant_new\wave2017.dta";
erase "H:\Mi unidad\Grant_new\wave2017_f.dta";


